<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('证券日分时图')" />
    <!-- 使用本地ECharts文件 -->
    <script th:src="@{/js/echarts.min.js}"></script>
    <!-- 备用CDN源（如果本地文件不可用） -->
    <!-- <script src="https://unpkg.com/echarts@5.4.3/dist/echarts.min.js"></script> -->
    <style>
        .security-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 20px;
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            margin-bottom: 20px;
        }
        
        .security-basic {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        .security-title {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .security-code {
            font-size: 20px;
            font-weight: bold;
            color: #333;
        }
        
        .security-name {
            font-size: 18px;
            color: #666;
        }
        
        .security-date {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .security-date-text {
            font-size: 14px;
            color: #888;
        }
        
        .security-weekday {
            font-size: 14px;
            color: #888;
            background: #f0f0f0;
            padding: 2px 8px;
            border-radius: 4px;
        }
        
        .date-navigation {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .date-nav-btn {
            width: 28px;
            height: 28px;
            border: 1px solid #ddd;
            background: white;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s;
            font-size: 14px;
            color: #666;
        }
        
        .date-nav-btn:hover {
            background: #f8f9fa;
            border-color: #007bff;
            color: #007bff;
        }
        
        .date-nav-btn:active {
            background: #e9ecef;
        }
        
        .date-nav-btn:disabled {
            background: #f5f5f5;
            border-color: #ddd;
            color: #ccc;
            cursor: not-allowed;
        }
        
        .security-price {
            text-align: right;
        }
        
        .current-price {
            font-size: 24px;
            font-weight: bold;
            color: #e74c3c;
        }
        
        .price-change {
            font-size: 14px;
            color: #e74c3c;
        }
        
        .chart-container {
            padding: 10px 30px;
            background: transparent;
        }
        
        #timeshare-chart {
            width: 100%;
            height: 500px;
            background: transparent;
            border: 1px solid #e8e8e8;
            border-radius: 4px;
        }
        
        
        .btn {
            padding: 8px 16px;
            border: 1px solid #ddd;
            background: white;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .btn:hover {
            background: #f8f9fa;
        }
        
        .btn.active {
            background: #007bff;
            color: white;
            border-color: #007bff;
        }
        
        .volume-chart {
            margin-top: 20px;
        }
        
        #volume-chart {
            width: 100%;
            height: 220px;
            background: transparent;
            border: 1px solid #e8e8e8;
            border-radius: 4px;
            margin-top: 10px;
        }
        
        .loading {
            text-align: center;
            padding: 50px;
            color: #666;
        }
        
        .error-message {
            text-align: center;
            padding: 20px;
            color: #e74c3c;
            background: #fdf2f2;
            border: 1px solid #f5c6cb;
            border-radius: 4px;
            margin: 20px;
        }
        
        .no-data {
            text-align: center;
            padding: 50px;
            color: #999;
            font-size: 16px;
        }
        
        /* 下拉框样式 */
        .dropdown-item {
            padding: 8px 12px;
            cursor: pointer;
            border-bottom: 1px solid #eee;
        }
        
        .dropdown-item:hover {
            background-color: #f5f5f5;
        }
        
        .dropdown-item.selected {
            background-color: #007bff !important;
            color: white !important;
        }
        
        #securityDropdown {
            display: none;
            position: absolute;
            top: 100%;
            left: 0;
            background: white;
            border: 1px solid #ccc;
            max-height: 200px;
            overflow-y: auto;
            z-index: 1000;
            width: 100%;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border-radius: 4px;
            margin-top: 2px;
        }
        
        /* 搜索框同行显示样式 */
        .current-security-info {
            font-size: 14px;
            width: 200px; /* 减少总宽度，因为改为两行 */
            flex-shrink: 0; /* 防止收缩 */
            display: flex;
            flex-direction: column; /* 改为垂直布局 */
            align-items: flex-start; /* 左对齐 */
            gap: 4px; /* 减少行间距 */
        }
        
        .security-display {
            display: flex;
            align-items: center;
            gap: 6px; /* 增加证券信息内部间距 */
            width: 100%; /* 占满宽度 */
            flex-shrink: 0; /* 防止收缩 */
        }
        
        .display-code {
            font-weight: bold;
            color: #333;
            background: #f8f9fa;
            padding: 2px 6px; /* 增加内边距 */
            border-radius: 3px;
            width: 80px; /* 增加宽度 */
            min-width: 80px; /* 确保最小宽度 */
            max-width: 80px; /* 确保最大宽度 */
            text-align: center; /* 居中对齐 */
            white-space: nowrap; /* 防止换行 */
            overflow: hidden; /* 隐藏溢出 */
            text-overflow: ellipsis; /* 显示省略号 */
            flex-shrink: 0; /* 防止收缩 */
            display: inline-block; /* 确保块级显示 */
            box-sizing: border-box; /* 包含padding在宽度内 */
            font-family: 'Courier New', monospace; /* 使用等宽字体 */
            font-size: 13px; /* 稍微减小字体大小 */
            line-height: 1.2; /* 固定行高 */
        }
        
        .display-name {
            color: #666;
            width: 100px; /* 增加宽度 */
            white-space: nowrap; /* 防止换行 */
            overflow: hidden; /* 隐藏溢出 */
            text-overflow: ellipsis; /* 显示省略号 */
            flex-shrink: 0; /* 防止收缩 */
        }
        
        .date-display {
            display: flex;
            align-items: center;
            gap: 6px; /* 增加日期信息内部间距 */
            width: 100%; /* 占满宽度 */
            flex-shrink: 0; /* 防止收缩 */
        }
        
        .display-date {
            color: #888;
            width: 100px; /* 增加宽度 */
            white-space: nowrap; /* 防止换行 */
            overflow: hidden; /* 隐藏溢出 */
            text-overflow: ellipsis; /* 显示省略号 */
            flex-shrink: 0; /* 防止收缩 */
        }
        
        .display-weekday {
            color: #888;
            background: #f0f0f0;
            padding: 2px 6px; /* 增加内边距 */
            border-radius: 3px;
            font-size: 12px;
            width: 45px; /* 增加宽度 */
            text-align: center; /* 居中对齐 */
            white-space: nowrap; /* 防止换行 */
            flex-shrink: 0; /* 防止收缩 */
        }
        
        /* 响应式处理 - 在小屏幕上调整布局 */
        @media (max-width: 1200px) {
            .current-security-info {
                width: 180px; /* 减少宽度 */
            }
            .display-code {
                width: 70px; /* 减小编码宽度 */
                min-width: 70px;
                max-width: 70px;
            }
            .display-name {
                width: 90px; /* 减少名称宽度 */
            }
            .display-date {
                width: 90px; /* 减少日期宽度 */
            }
            .display-weekday {
                width: 40px; /* 减少周几宽度 */
            }
        }
        
        @media (max-width: 992px) {
            .current-security-info {
                width: 160px;
            }
            .display-name {
                width: 70px; /* 进一步减小名称宽度 */
            }
            .display-date {
                width: 80px; /* 进一步减小日期宽度 */
            }
            .display-code {
                width: 60px; /* 进一步减小编码宽度 */
                min-width: 60px;
                max-width: 60px;
            }
            .display-weekday {
                width: 35px; /* 进一步减小周几宽度 */
            }
        }
        
        /* 同步弹窗样式 */
        .timeshare-sync-modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 10000;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .timeshare-sync-modal-content {
            background: white;
            border-radius: 8px;
            width: 550px;
            max-width: 90%;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
            animation: modalFadeIn 0.2s ease-out;
        }
        
        @keyframes modalFadeIn {
            from {
                opacity: 0;
                transform: scale(0.9);
            }
            to {
                opacity: 1;
                transform: scale(1);
            }
        }
        
        .timeshare-sync-modal-header {
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .timeshare-sync-modal-header h3 {
            margin: 0;
            font-size: 16px;
            font-weight: 600;
            color: #333;
        }
        
        .timeshare-sync-modal-close {
            background: none;
            border: none;
            font-size: 24px;
            color: #999;
            cursor: pointer;
            padding: 0;
            width: 24px;
            height: 24px;
            line-height: 24px;
            text-align: center;
        }
        
        .timeshare-sync-modal-close:hover {
            color: #333;
        }
        
        .timeshare-sync-modal-body {
            padding: 20px;
            min-height: 120px;
        }
        
        .timeshare-sync-modal-footer {
            padding: 15px 20px;
            border-top: 1px solid #eee;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }
        
        .sync-date-range-container {
            display: flex;
            gap: 20px;
            margin-bottom: 15px;
        }
        
        .sync-date-item {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .sync-date-item label {
            font-size: 14px;
            color: #333;
            white-space: nowrap;
        }
        
        .sync-quick-select-container {
            display: flex;
            align-items: center;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #eee;
        }
        
        .sync-quick-select-btn {
            padding: 6px 12px;
            margin-right: 8px;
            border: 1px solid #ddd;
            background: white;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
            transition: all 0.3s;
        }
        
        .sync-quick-select-btn:hover {
            background: #f8f9fa;
        }
        
        .sync-quick-select-btn.active {
            background: #007bff;
            color: white;
            border-color: #007bff;
        }
        
        .sync-data-btn {
            padding: 8px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }
        
        .sync-data-btn-cancel {
            background: #f5f5f5;
            color: #666;
        }
        
        .sync-data-btn-cancel:hover {
            background: #e0e0e0;
        }
        
        .sync-data-btn-confirm {
            background: #007bff;
            color: white;
        }
        
        .sync-data-btn-confirm:hover {
            background: #0056b3;
        }
        
        .sync-data-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        .sync-progress-bar {
            width: 100%;
            height: 20px;
            background: #f0f0f0;
            border-radius: 10px;
            overflow: hidden;
            position: relative;
        }
        
        .sync-progress-bar-fill {
            height: 100%;
            background: linear-gradient(90deg, #007bff, #0056b3);
            transition: width 0.3s ease;
            border-radius: 10px;
        }
    </style>
</head>
<body class="gray-bg">
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <form id="security-form">
                <div class="select-list">
                    <ul>
                        <li style="position: relative; display: flex; align-items: center; gap: 15px; flex-wrap: nowrap; min-height: 40px;">
                            <div style="display: flex; flex-direction: column; gap: 8px;">
                                <div style="display: flex; align-items: center; gap: 8px;">
                                    <span style="width: 72px; display: inline-block;">选择证券：</span>
                                    <div style="position: relative; width: 180px;">
                                        <input type="text" id="securitySelect" placeholder="请输入名称或代码" style="width: 100%; text-align: center;" autocomplete="off"/>
                                        <input type="hidden" id="securitySymbol" name="symbol"/>
                                        <div id="securityDropdown" style="display: none; position: absolute; top: 100%; left: 0; background: white; border: 1px solid #ccc; max-height: 200px; overflow-y: auto; z-index: 1000; width: 100%; box-shadow: 0 2px 8px rgba(0,0,0,0.1); border-radius: 4px; margin-top: 2px;"></div>
                                    </div>
                                </div>
                                <div class="security-display" style="display: flex; align-items: center; gap: 2px; margin-left: 80px; min-width: 180px; justify-content: flex-start; flex-wrap: nowrap; overflow: visible;">
                                    <span class="display-name" id="displayName" style="font-size: 15px; color: #007bff; font-weight: bold; white-space: nowrap; flex-shrink: 1; display: inline-block; max-width: 90px; overflow: hidden; text-overflow: ellipsis;">上证指数</span>
                                    <span class="display-code" id="displayCode" style="font-size: 15px; color: #28a745; font-weight: bold; white-space: nowrap; flex-shrink: 0; display: inline-block; min-width: 90px;">SH000001</span>
                                </div>
                            </div>
                            <div style="display: flex; flex-direction: column; gap: 8px;">
                                <div style="display: flex; align-items: center; gap: 8px;">
                                    <span style="width: 72px; display: inline-block;">选择日期：</span>
                                    <div style="position: relative;">
                                        <input type="text" id="dateSelect" placeholder="选择日期" readonly style="width: 120px; padding: 5px; border: 1px solid #ddd; border-radius: 4px; cursor: pointer;"/>
                                        <div id="dateCalendar" style="display: none; position: absolute; top: 100%; left: 0; background: white; border: 1px solid #ddd; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); z-index: 1000; width: 280px; padding: 10px; margin-top: 2px;"></div>
                                    </div>
                                </div>
                                <div class="date-navigation" style="display: flex; align-items: center; gap: 8px; margin-left: 80px;">
                                    <span class="display-weekday" id="displayWeekday" style="font-size: 14px; color: #888; background: #f0f0f0; padding: 2px 8px; border-radius: 4px; margin-right: 4px;">周一</span>
                                    <button type="button" class="date-nav-btn" id="prevDateBtn" title="上一日">‹</button>
                                    <button type="button" class="date-nav-btn" id="nextDateBtn" title="下一日">›</button>
                                </div>
                            </div>
                            <div style="display: flex; align-items: center; gap: 15px;">
                                <div class="security-price-info" style="display: flex; flex-direction: column; align-items: flex-start; gap: 2px;">
                                    <div class="security-price-value" id="headerCurrentPrice" style="font-size: 34px; font-weight: bold; color: #333; line-height: 1.2;">N/A</div>
                                    <div class="security-price-change" id="headerPriceChange" style="font-size: 12px; color: #666; line-height: 1.2;">N/A</div>
                                </div>
                                <div class="security-price-details" style="display: flex; flex-direction: column; align-items: flex-start; gap: 4px; margin-left: 10px;">
                                    <div style="font-size: 12px; color: #666; line-height: 1.2; display: flex; align-items: center;">
                                        <span style="color: #999; width: 3.5em; display: inline-block; white-space: nowrap; text-align: left;">最　高:</span>
                                        <span id="headerHighestPrice" style="color: #333; width: 100px; display: inline-block; text-align: left;">N/A</span>
                                        <span style="color: #999; margin-left: 8px; width: 3.5em; display: inline-block; white-space: nowrap; text-align: left;">涨　跌:</span>
                                        <span id="headerRiseFall" style="color: #333; width: 100px; display: inline-block;"></span>
                                    </div>
                                    <div style="font-size: 12px; color: #666; line-height: 1.2; display: flex; align-items: center;">
                                        <span style="color: #999; width: 3.5em; display: inline-block; white-space: nowrap; text-align: left;">最　低:</span>
                                        <span id="headerLowestPrice" style="color: #333; width: 100px; display: inline-block; text-align: left;">N/A</span>
                                        <span style="color: #999; margin-left: 8px; width: 3.5em; display: inline-block; white-space: nowrap; text-align: left;">振　幅:</span>
                                        <span id="headerAmplitude" style="color: #333; width: 120px; display: inline-block;"></span>
                                    </div>
                                    <div style="font-size: 12px; color: #666; line-height: 1.2; display: flex; align-items: center;">
                                        <span style="color: #999; width: 3.5em; display: inline-block; white-space: nowrap; text-align: left;">今　开:</span>
                                        <span id="headerOpenPrice" style="color: #333; width: 100px; display: inline-block; text-align: left;">N/A</span>
                                    </div>
                                    <div style="font-size: 12px; color: #666; line-height: 1.2; display: flex; align-items: center;">
                                        <span style="color: #999; width: 3.5em; display: inline-block; white-space: nowrap; text-align: left;">昨　收:</span>
                                        <span id="headerPreviousClosePrice" style="color: #000; width: 60px; display: inline-block; text-align: left;">N/A</span>
                                    </div>
                                </div>
                                <div class="period-buttons" style="display: flex; gap: 8px; align-items: center;">
                                    <button type="button" class="btn active" onclick="switchPeriod('1d', event)">日线</button>
                                    <button type="button" class="btn" onclick="switchPeriod('5d', event)">5日线</button>
                                    <button type="button" class="btn" onclick="showSyncTimeshareModal()" style="margin-left: 10px; background: #28a745; color: white; border-color: #28a745;">同步分时数据</button>
                                </div>
                            </div>
                        </li>
                    </ul>
                </div>
            </form>
        </div>
        
        <div class="col-sm-12">
            <div class="security-info" th:if="${securityInfo}">
                <div class="security-basic">
                    <div class="security-title">
                        <span class="security-code" id="securityCode" th:text="${securityInfo.code}">000001</span>
                        <span class="security-name" id="securityName" th:text="${securityInfo.name}">上证指数</span>
                    </div>
                    <div class="security-date">
                        <div class="date-navigation">
                            <button type="button" class="date-nav-btn" id="prevDateBtn" title="上一日">‹</button>
                            <span class="security-date-text" id="securityDate">2024-01-15</span>
                            <span class="security-weekday" id="securityWeekday">周一</span>
                            <button type="button" class="date-nav-btn" id="nextDateBtn" title="下一日">›</button>
                        </div>
                    </div>
                </div>
                <div class="security-price">
                    <div class="current-price" id="currentPrice">3000.00</div>
                    <div class="price-change" id="priceChange">+0.00 (+0.00%)</div>
                </div>
            </div>
            
            <div class="chart-container">
                
                <div id="timeshare-chart"></div>
                
                <div class="volume-chart">
                    <div id="volume-chart"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 同步分时数据模态框 -->
<div id="syncTimeshareModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); z-index: 10000; justify-content: center; align-items: center;">
    <div style="background: white; border-radius: 8px; width: 600px; max-width: 90%; padding: 20px; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3 style="margin: 0;">同步分时数据</h3>
            <button type="button" id="syncTimeshareModalClose" style="background: none; border: none; font-size: 24px; color: #999; cursor: pointer;">&times;</button>
        </div>
        <!-- 日期选择在同一行 -->
        <div style="display: flex; gap: 15px; margin-bottom: 15px; justify-content: center;">
            <div style="width: 180px;">
                <label style="display: block; margin-bottom: 5px; font-weight: bold; text-align: center;">开始日期：</label>
                <div style="position: relative;">
                    <input type="text" id="syncTimeshareStartDate" placeholder="选择开始日期" readonly style="width: 100%; padding: 6px; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; font-size: 13px;"/>
                    <div id="syncTimeshareStartDateCalendar" style="display: none; position: absolute; top: 100%; left: 0; background: white; border: 1px solid #ddd; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); z-index: 10001; width: 280px; padding: 10px; margin-top: 2px;"></div>
                </div>
            </div>
            <div style="width: 180px;">
                <label style="display: block; margin-bottom: 5px; font-weight: bold; text-align: center;">结束日期：</label>
                <div style="position: relative;">
                    <input type="text" id="syncTimeshareEndDate" placeholder="选择结束日期" readonly style="width: 100%; padding: 6px; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; font-size: 13px;"/>
                    <div id="syncTimeshareEndDateCalendar" style="display: none; position: absolute; top: 100%; left: 0; background: white; border: 1px solid #ddd; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); z-index: 10001; width: 280px; padding: 10px; margin-top: 2px;"></div>
                </div>
            </div>
        </div>
        <!-- 快捷日期选择按钮 -->
        <div style="margin-bottom: 20px;">
            <div style="display: flex; gap: 8px; flex-wrap: wrap; justify-content: center;">
                <button type="button" class="sync-quick-date-btn" data-days="0" style="padding: 6px 12px; background: #f5f5f5; color: #666; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; font-size: 13px;">当日</button>
                <button type="button" class="sync-quick-date-btn" data-days="5" style="padding: 6px 12px; background: #f5f5f5; color: #666; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; font-size: 13px;">5日</button>
                <button type="button" class="sync-quick-date-btn" data-months="1" style="padding: 6px 12px; background: #f5f5f5; color: #666; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; font-size: 13px;">1月</button>
                <button type="button" class="sync-quick-date-btn" data-months="3" style="padding: 6px 12px; background: #f5f5f5; color: #666; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; font-size: 13px;">3月</button>
                <button type="button" class="sync-quick-date-btn" data-months="6" style="padding: 6px 12px; background: #f5f5f5; color: #666; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; font-size: 13px;">6月</button>
                <button type="button" class="sync-quick-date-btn" data-months="12" style="padding: 6px 12px; background: #f5f5f5; color: #666; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; font-size: 13px;">1年</button>
            </div>
        </div>
        <!-- 进度条 -->
        <div id="syncTimeshareProgress" style="display: none; margin-bottom: 20px;">
            <div style="margin-bottom: 10px;">
                <div style="width: 100%; height: 28px; background: #e9ecef; border-radius: 14px; overflow: hidden; position: relative; box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);">
                    <div id="syncTimeshareProgressBar" style="height: 100%; background: linear-gradient(90deg, #28a745 0%, #34ce57 50%, #20c997 100%); transition: width 0.3s ease; border-radius: 14px; width: 0%; box-shadow: 0 2px 4px rgba(40, 167, 69, 0.3);"></div>
                    <div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; font-size: 15px; font-weight: 700; color: #fff; text-shadow: 0 2px 4px rgba(0,0,0,0.5), 0 0 8px rgba(0,0,0,0.3), 0 0 2px rgba(255,255,255,0.5); z-index: 1; letter-spacing: 1px;">
                        <span id="syncTimeshareProgressText">0% (0/0)</span>
                    </div>
                </div>
            </div>
            <div style="margin-bottom: 8px; font-size: 12px; color: #666;">
                <span>当前同步: <span id="syncTimeshareCurrentDate" style="color: #007bff; font-weight: bold;">-</span></span>
                <span style="margin-left: 15px;">进度: <span id="syncTimeshareProgressDetail">0 天 / 0 天</span></span>
            </div>
            <div style="display: flex; justify-content: space-between; font-size: 12px; color: #666;">
                <span>已同步时间: <span id="syncTimeshareElapsedTime">00:00:00</span></span>
                <span>预计同步时间: <span id="syncTimeshareEstimatedTime">00:00:00</span></span>
                <span>剩余同步时间: <span id="syncTimeshareRemainingTime">00:00:00</span></span>
            </div>
        </div>
        <div style="display: flex; justify-content: flex-end; gap: 10px;">
            <button type="button" id="syncTimeshareModalCancel" style="padding: 8px 20px; background: #f5f5f5; color: #666; border: 1px solid #ddd; border-radius: 4px; cursor: pointer;">取消</button>
            <button type="button" id="syncTimeshareModalConfirm" style="padding: 8px 20px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">确定</button>
        </div>
    </div>
</div>

<th:block th:include="include :: footer" />
<!-- 证券选择组件 - 必须在 jQuery 加载后 -->
<script th:src="@{/js/security-selector.js}"></script>
<!-- 证券日期选择组件 - 必须在 jQuery 加载后 -->
<script th:src="@{/js/security-date-picker.js}"></script>
<script th:inline="javascript">
    // 若依框架变量
    var prefix = ctx + "security/";
    var currentSecuritySymbol = /*[[${securityInfo?.symbol}]]*/ "sh000001"; // 默认上证指数
    var currentPeriod = /*[[${currentPeriod}]]*/ "1d"; // 默认日线
    var securityDatePicker = null; // 证券日期选择组件实例
    var securitySelector = null; // 证券选择组件实例
    
    // 确保变量不为空
    if (!currentSecuritySymbol) {
        currentSecuritySymbol = "sh000001";
    }
    if (!currentPeriod) {
        currentPeriod = "1d";
    }
    
    // 初始化图表
    let timeshareChart = null;
    let volumeChart = null;
    
    $(function() {
        // 初始化图表
        initCharts();
        
        // 初始化证券选择组件
        securitySelector = new SecuritySelector({
            inputId: 'securitySelect',
            dropdownId: 'securityDropdown',
            symbolInputId: 'securitySymbol',
            apiPrefix: prefix,
            enableHistory: true, // 启用搜索历史
            enableDeleteAll: true,
            onSelect: function(security) {
                console.log("证券被选择:", security);
                currentSecuritySymbol = security.symbol;
                // 立即更新显示信息
                // 显示完整的symbol，并将符号部分大写（如sh000001 -> SH000001）
                var displaySymbol = security.symbol ? security.symbol.toUpperCase() : (security.code || '');
                $("#displayCode").text(displaySymbol);
                $("#displayName").text(security.name);
                // 加载证券数据
                loadSecurityData();
            }
        });
        securitySelector.init();
        
        // 设置默认证券（如果有）
        if (currentSecuritySymbol) {
            // 等待证券列表加载完成后设置默认值
            setTimeout(function() {
                var defaultSecurity = securitySelector.securitiesList.find(function(security) {
                    return security.symbol === currentSecuritySymbol;
                });
                if (defaultSecurity) {
                    securitySelector.setSelectedSecurity(defaultSecurity);
                    // 更新显示信息
                    var displaySymbol = defaultSecurity.symbol ? defaultSecurity.symbol.toUpperCase() : (defaultSecurity.code || '');
                    $("#displayCode").text(displaySymbol);
                    $("#displayName").text(defaultSecurity.name);
                }
            }, 500);
        }
        
        // 计算当前时间和最大可选日期
        var now = new Date();
        var currentHour = now.getHours();
        var currentMinute = now.getMinutes();
        var isAfter1500 = (currentHour > 15) || (currentHour === 15 && currentMinute >= 0);
        
        // 如果当前时间大于15:00，最大可选日期为今天；否则为昨天
        var maxDate = null;
        if (isAfter1500) {
            maxDate = new Date(now);
        } else {
            var yesterday = new Date(now);
            yesterday.setDate(yesterday.getDate() - 1);
            maxDate = yesterday;
        }
        
        // 初始化证券日期选择组件
        securityDatePicker = new SecurityDatePicker({
            inputId: 'dateSelect',
            calendarId: 'dateCalendar',
            apiPrefix: prefix,
            maxDate: maxDate,
            autoInitDate: true,
            onDateSelect: function(date) {
                console.log('日期选择回调被触发，日期:', date);
                // 更新周几显示（从交易日历中获取）
                updateWeekdayFromCalendar(date);
                loadSecurityData();
            }
        });
        securityDatePicker.init();
        console.log('证券日期选择组件初始化完成');
        
        // 左右箭头按钮事件处理
        $("#prevDateBtn").on('click', function() {
            navigateToPreviousDay();
        });
        
        $("#nextDateBtn").on('click', function() {
            navigateToNextDay();
        });
        
        // 调试信息
        console.log("页面初始化 - currentSecuritySymbol:", currentSecuritySymbol, "currentPeriod:", currentPeriod);
        
        // 日期选择组件的事件绑定已在组件内部处理
        
        // 检查URL参数，如果是从回测页面跳转过来的，自动打开同步模态框
        var urlParams = new URLSearchParams(window.location.search);
        var syncParam = urlParams.get('sync');
        var symbolParam = urlParams.get('symbol');
        var startDateParam = urlParams.get('startDate');
        var endDateParam = urlParams.get('endDate');
        var returnUrlParam = urlParams.get('returnUrl'); // 返回URL
        
        // 保存返回URL到全局变量
        if (returnUrlParam) {
            window.syncReturnUrl = decodeURIComponent(returnUrlParam);
        }
        
        if (syncParam === 'true' && symbolParam && startDateParam && endDateParam) {
            // 设置当前证券
            currentSecuritySymbol = symbolParam;
            
            // 等待页面完全加载后，打开同步模态框并填充参数
            setTimeout(function() {
                // 如果证券选择器已初始化，设置选中的证券
                if (securitySelector) {
                    var targetSecurity = securitySelector.securitiesList.find(function(security) {
                        return security.symbol === symbolParam;
                    });
                    if (targetSecurity) {
                        securitySelector.setSelectedSecurity(targetSecurity);
                        var displaySymbol = targetSecurity.symbol ? targetSecurity.symbol.toUpperCase() : (targetSecurity.code || '');
                        $("#displayCode").text(displaySymbol);
                        $("#displayName").text(targetSecurity.name);
                    }
                }
                
                // 打开同步模态框
                showSyncTimeshareModal();
                
                // 延迟设置日期（等待日期选择器初始化完成）
                setTimeout(function() {
                    if (syncTimeshareStartDatePicker) {
                        // 找到最近的交易日
                        var nearestStartDate = syncTimeshareStartDatePicker.findNearestTradingDay ? 
                            syncTimeshareStartDatePicker.findNearestTradingDay(startDateParam) : startDateParam;
                        syncTimeshareStartDatePicker.setDate(nearestStartDate);
                    }
                    if (syncTimeshareEndDatePicker) {
                        // 找到最近的交易日
                        var nearestEndDate = syncTimeshareEndDatePicker.findNearestTradingDay ? 
                            syncTimeshareEndDatePicker.findNearestTradingDay(endDateParam) : endDateParam;
                        syncTimeshareEndDatePicker.setDate(nearestEndDate);
                    }
                }, 300);
                
                // 清除URL参数，避免刷新时重复打开
                var newUrl = window.location.pathname;
                window.history.replaceState({}, document.title, newUrl);
            }, 500);
        }
        
        // 如果有服务器端数据，直接使用；否则加载数据
        /*[# th:if="${securityInfo}"]*/
        // 服务器端已有数据，直接更新图表
        var serverTimeshareData = /*[[${timeshareData}]]*/ null;
        var serverVolumeData = /*[[${volumeData}]]*/ null;
        if (serverTimeshareData && serverVolumeData) {
            updateCharts(serverTimeshareData, serverVolumeData);
        } else {
            loadSecurityData();
        }
        /*[/]*/
        /*[# th:unless="${securityInfo}"]*/
        // 服务器端没有数据，加载默认数据
        loadSecurityData();
        /*[/]*/
    });
    
    // 初始化图表
    function initCharts() {
        timeshareChart = echarts.init(document.getElementById('timeshare-chart'));
        volumeChart = echarts.init(document.getElementById('volume-chart'));
        
        // 窗口大小改变时重新调整图表
        window.addEventListener('resize', function() {
            if (timeshareChart) timeshareChart.resize();
            if (volumeChart) volumeChart.resize();
        });
        
        // 页面卸载时清理定时器，避免内存泄漏和错误
        $(window).on('beforeunload', function() {
            stopPollingProgress();
        });
    }
    
    

    // 导航到上一日（使用交易日历）
    function navigateToPreviousDay() {
        if (!securityDatePicker) {
            $.modal.msgWarning("日期选择器未初始化");
            return;
        }
        
        var currentDate = securityDatePicker.getSelectedDate();
        if (!currentDate) {
            $.modal.msgWarning("请先选择日期");
            return;
        }
        
        // 直接从交易日历获取上一个交易日
        var previousDate = null;
        if (securityDatePicker.tradingCalendarData && Object.keys(securityDatePicker.tradingCalendarData).length > 0) {
            // 遍历交易日历，找到小于当前日期的最近一个交易日
            var tradingDaysList = [];
            for (var dateStr in securityDatePicker.tradingCalendarData) {
                var item = securityDatePicker.tradingCalendarData[dateStr];
                if (item && item.tradingDayFlag === 1 && dateStr < currentDate) {
                    tradingDaysList.push(dateStr);
                }
            }
            // 按日期倒序排列，返回最近的一个交易日
            tradingDaysList.sort().reverse();
            if (tradingDaysList.length > 0) {
                previousDate = tradingDaysList[0];
            }
        }
        
        // 如果交易日历数据未加载，使用组件方法
        if (!previousDate && securityDatePicker.findPreviousTradingDay) {
            previousDate = securityDatePicker.findPreviousTradingDay(currentDate);
        }
        
        if (previousDate) {
            // 设置新日期并重新加载数据
            securityDatePicker.setDate(previousDate);
            // 立即更新周几显示
            updateWeekdayFromCalendar(previousDate);
            loadSecurityData();
        } else {
            $.modal.msgWarning("无法找到上一个交易日");
        }
    }
    
    // 导航到下一日（使用交易日历）
    function navigateToNextDay() {
        if (!securityDatePicker) {
            $.modal.msgWarning("日期选择器未初始化");
            return;
        }
        
        var currentDate = securityDatePicker.getSelectedDate();
        if (!currentDate) {
            $.modal.msgWarning("请先选择日期");
            return;
        }
        
        // 计算最大可选日期
        var now = new Date();
        var currentHour = now.getHours();
        var currentMinute = now.getMinutes();
        var isAfter1500 = (currentHour > 15) || (currentHour === 15 && currentMinute >= 0);
        var maxDate = null;
        if (isAfter1500) {
            maxDate = new Date(now);
        } else {
            var yesterday = new Date(now);
            yesterday.setDate(yesterday.getDate() - 1);
            maxDate = yesterday;
        }
        var maxDateStr = maxDate.toISOString().split('T')[0];
        
        if (currentDate >= maxDateStr) {
            $.modal.msgWarning("已到达最新交易日");
            return;
        }
        
        // 直接从交易日历获取下一个交易日
        var nextDate = null;
        if (securityDatePicker.tradingCalendarData && Object.keys(securityDatePicker.tradingCalendarData).length > 0) {
            // 遍历交易日历，找到大于当前日期的最近一个交易日
            var tradingDaysList = [];
            for (var dateStr in securityDatePicker.tradingCalendarData) {
                var item = securityDatePicker.tradingCalendarData[dateStr];
                if (item && item.tradingDayFlag === 1 && dateStr > currentDate && dateStr <= maxDateStr) {
                    tradingDaysList.push(dateStr);
                }
            }
            // 按日期正序排列，返回最近的一个交易日
            tradingDaysList.sort();
            if (tradingDaysList.length > 0) {
                nextDate = tradingDaysList[0];
            }
        }
        
        // 如果交易日历数据未加载，使用组件方法
        if (!nextDate && securityDatePicker.findNextTradingDay) {
            nextDate = securityDatePicker.findNextTradingDay(currentDate);
            // 检查是否超过最大可选日期
            if (nextDate && nextDate > maxDateStr) {
                nextDate = null;
            }
        }
        
        if (nextDate) {
            // 设置新日期并重新加载数据
            securityDatePicker.setDate(nextDate);
            // 立即更新周几显示
            updateWeekdayFromCalendar(nextDate);
            loadSecurityData();
        } else {
            $.modal.msgWarning("已到达最新交易日");
        }
    }
    
    // 加载证券数据
    function loadSecurityData() {
        var securitySymbol = currentSecuritySymbol || "sh000001";
        
        // 从组件获取选中的证券
        if (securitySelector) {
            var selectedSecurity = securitySelector.getSelectedSecurity();
            if (selectedSecurity) {
                securitySymbol = selectedSecurity.symbol;
                currentSecuritySymbol = securitySymbol;
            } else {
                // 如果没有选中的证券，尝试从隐藏字段获取
                var symbolValue = $("#securitySymbol").val();
                if (symbolValue) {
                    securitySymbol = symbolValue;
                    currentSecuritySymbol = securitySymbol;
                }
            }
        }
        
        // 确保参数不为空
        if (!securitySymbol || securitySymbol.trim() === "") {
            securitySymbol = "sh000001";
        }
        if (!currentPeriod || currentPeriod.trim() === "") {
            currentPeriod = "1d";
        }
        
        // 更新当前证券代码
        if (securitySymbol) {
            currentSecuritySymbol = securitySymbol;
        }
        
        // 显示加载状态
        showLoading();
        
        // 计算开始和结束日期
        var startDate, endDate;
        var currentDate = securityDatePicker ? securityDatePicker.getSelectedDate() : null;
        if (currentDate) {
            // 如果选择了特定日期，根据周期计算开始日期
            endDate = currentDate;
            startDate = calculateStartDate(currentDate, currentPeriod);
        } else {
            // 如果没有选择日期，使用默认逻辑
            var today = new Date();
            var todayStr = today.toISOString().split('T')[0];
            if (securityDatePicker) {
                endDate = securityDatePicker.findNearestTradingDay(todayStr);
            } else {
                endDate = todayStr;
            }
            startDate = calculateStartDate(endDate, currentPeriod);
        }
        
        // 调用后端接口获取证券数据
        var requestData = {
            symbol: securitySymbol,
            startDate: startDate,
            endDate: endDate
        };
        
        console.log("请求参数:", requestData);
        $.ajax({
            url: prefix + "time-share/data",
            type: "GET",
            data: requestData,
            dataType: 'json',
            success: function(data) {
                console.log("分时数据API响应:", data);
                
                if (data.code !== 0) {
                    console.log("API返回错误:", data.msg);
                    showErrorMessage(data.msg || "获取数据失败");
                    // 如果接口失败，使用模拟数据
                    loadMockData();
                    return;
                }
                
                // 获取实际数据
                var responseData = data.data;
                console.log("分时数据响应内容:", responseData);
                
                if (responseData) {
                    // 更新证券信息
                    if (responseData.securityInfo) {
                        console.log("更新证券信息:", responseData.securityInfo);
                        updateSecurityInfo(responseData.securityInfo);
                    }
                    // 更新图表数据
                    if (responseData.timeshareData && responseData.volumeData) {
                        console.log("使用接口数据更新图表");
                        console.log("分时数据:", responseData.timeshareData);
                        console.log("涨跌幅数据:", responseData.changePercentData);
                        console.log("均线数据:", responseData.averagePriceData);
                        console.log("成交量数据:", responseData.volumeData);
                        // 保存日期范围，用于生成x轴标签
                        window.currentStartDate = startDate;
                        window.currentEndDate = endDate;
                        updateCharts(responseData.timeshareData, responseData.changePercentData, responseData.averagePriceData, responseData.volumeData);
                        
                        // 更新图表后，再次更新价格信息（使用收盘价）
                        if (responseData.securityInfo) {
                            updateSecurityInfo(responseData.securityInfo);
                        }
                    } else {
                        console.log("接口没有返回图表数据，使用模拟数据");
                        // 如果没有图表数据，使用模拟数据
                        loadMockData();
                    }
                } else {
                    console.log("接口返回数据为空，使用模拟数据");
                    // 如果没有数据，使用模拟数据
                    loadMockData();
                }
                
                // 更新按钮状态
                updateDateNavigationButtons();
            },
            error: function(xhr, status, error) {
                console.error("数据加载失败:", error);
                showErrorMessage("网络连接失败，请检查网络后重试");
                // 如果接口失败，使用模拟数据
                loadMockData();
                // 更新按钮状态
                updateDateNavigationButtons();
            }
        });
    }
    
    // 加载模拟数据（备用方案）
    function loadMockData() {
        var mockData = generateTimeshareData();
        updateCharts(mockData.priceData, mockData.changePercentData, mockData.averagePriceData, mockData.volumeData);
    }
    
    // 生成模拟证券分时数据
    function generateTimeshareData() {
        const data = [];
        const changePercentData = [];
        const averagePriceData = [];
        const volumeData = [];
        const basePrice = 3000.0; // 上证指数基准价格
        const baseVolume = 1000000;
        
        // 生成9:30-15:00的交易时间数据
        for (let i = 0; i < 240; i++) {
            const hour = Math.floor(i / 60) + 9;
            const minute = i % 60;
            
            // 跳过11:30-13:00的午休时间
            if (hour === 11 && minute >= 30) continue;
            if (hour === 12) continue;
            if (hour === 13 && minute === 0) continue;
            
            const time = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
            
            // 模拟价格波动（指数波动相对较小）
            const priceChange = (Math.random() - 0.5) * 20;
            const price = basePrice + priceChange + Math.sin(i * 0.05) * 10;
            
            // 计算涨跌幅
            const changePercent = ((price - basePrice) / basePrice * 100).toFixed(2);
            
            // 模拟均价（比价格稍微平滑一些）
            const averagePrice = basePrice + priceChange * 0.8 + Math.sin(i * 0.05) * 8;
            
            // 模拟成交量
            const volume = baseVolume + Math.random() * 500000;
            
            data.push([time, price.toFixed(2)]);
            changePercentData.push([time, changePercent]);
            averagePriceData.push([time, averagePrice.toFixed(2)]);
            volumeData.push([time, Math.floor(volume)]);
        }
        
        return { 
            priceData: data, 
            changePercentData: changePercentData, 
            averagePriceData: averagePriceData,
            volumeData: volumeData 
        };
    }
    
    // 更新按钮状态（使用交易日历）
    function updateDateNavigationButtons() {
        if (!securityDatePicker) {
            $("#prevDateBtn").prop('disabled', true);
            $("#nextDateBtn").prop('disabled', true);
            return;
        }
        
        var currentDate = securityDatePicker.getSelectedDate();
        if (!currentDate) {
            $("#prevDateBtn").prop('disabled', true);
            $("#nextDateBtn").prop('disabled', true);
            return;
        }
        
        // 计算最大可选日期
        var now = new Date();
        var currentHour = now.getHours();
        var currentMinute = now.getMinutes();
        var isAfter1500 = (currentHour > 15) || (currentHour === 15 && currentMinute >= 0);
        var maxDate = null;
        if (isAfter1500) {
            maxDate = new Date(now);
        } else {
            var yesterday = new Date(now);
            yesterday.setDate(yesterday.getDate() - 1);
            maxDate = yesterday;
        }
        var maxDateStr = maxDate.toISOString().split('T')[0];
        
        // 直接从交易日历检查是否有上一个交易日
        var hasPrevious = false;
        if (securityDatePicker.tradingCalendarData && Object.keys(securityDatePicker.tradingCalendarData).length > 0) {
            for (var dateStr in securityDatePicker.tradingCalendarData) {
                var item = securityDatePicker.tradingCalendarData[dateStr];
                if (item && item.tradingDayFlag === 1 && dateStr < currentDate) {
                    hasPrevious = true;
                    break;
                }
            }
        } else if (securityDatePicker.findPreviousTradingDay) {
            // 如果交易日历数据未加载，使用组件方法
            var previousDate = securityDatePicker.findPreviousTradingDay(currentDate);
            hasPrevious = previousDate && previousDate !== currentDate;
        }
        
        // 直接从交易日历检查是否有下一个交易日
        var hasNext = false;
        if (securityDatePicker.tradingCalendarData && Object.keys(securityDatePicker.tradingCalendarData).length > 0) {
            for (var dateStr in securityDatePicker.tradingCalendarData) {
                var item = securityDatePicker.tradingCalendarData[dateStr];
                if (item && item.tradingDayFlag === 1 && dateStr > currentDate && dateStr <= maxDateStr) {
                    hasNext = true;
                    break;
                }
            }
        } else if (securityDatePicker.findNextTradingDay) {
            // 如果交易日历数据未加载，使用组件方法
            var nextDate = securityDatePicker.findNextTradingDay(currentDate);
            hasNext = nextDate && nextDate <= maxDateStr;
        }
        
        $("#prevDateBtn").prop('disabled', !hasPrevious);
        $("#nextDateBtn").prop('disabled', !hasNext);
    }
    
    // 从交易日历更新周几显示
    function updateWeekdayFromCalendar(date) {
        var weekday = null;
        if (securityDatePicker && date && securityDatePicker.tradingCalendarData) {
            var calendarItem = securityDatePicker.tradingCalendarData[date];
            if (calendarItem && calendarItem.weekday) {
                // 交易日历中的weekday：1-周日，2-周一，3-周二，4-周三，5-周四，6-周五，7-周六
                var weekdays = ['', '周日', '周一', '周二', '周三', '周四', '周五', '周六'];
                weekday = weekdays[calendarItem.weekday];
            }
        }
        
        // 如果交易日历中没有，根据日期计算
        if (!weekday && date) {
            var dateObj = new Date(date);
            var weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
            weekday = weekdays[dateObj.getDay()];
        }
        
        if (weekday) {
            $("#securityWeekday").text(weekday);
            $("#displayWeekday").text(weekday);
        }
    }
    
    // 更新证券信息
    function updateSecurityInfo(securityInfo) {
        if (securityInfo) {
            // 保存到全局变量，供图表使用
            window.currentSecurityInfo = securityInfo;
            
            // 更新证券代码和名称（图表区域）
            $("#securityCode").text(securityInfo.code || "000001");
            $("#securityName").text(securityInfo.name || "上证指数");
            
            // 更新搜索框同行右侧的显示信息
            // 优先使用后端返回的数据，如果后端有返回则覆盖前端显示的值
            if (securityInfo.symbol) {
                // 显示完整的symbol，并将符号部分大写（如sh000001 -> SH000001）
                $("#displayCode").text(securityInfo.symbol.toUpperCase());
            } else if (securityInfo.code) {
                $("#displayCode").text(securityInfo.code);
            }
            if (securityInfo.name) {
                $("#displayName").text(securityInfo.name);
            }
            
            // 更新日期信息（图表区域）
            var dateStr;
            if (securityInfo.date) {
                dateStr = new Date(securityInfo.date).toLocaleDateString('zh-CN');
            } else {
                // 如果没有日期信息，显示当前日期
                dateStr = new Date().toLocaleDateString('zh-CN');
            }
            $("#securityDate").text(dateStr);
            
            // 更新周几信息（从交易日历中获取，与选择日期框对应）
            var weekday = null;
            // 优先从交易日历中获取当前选择日期的周几
            if (securityDatePicker) {
                var currentDate = securityDatePicker.getSelectedDate();
                if (currentDate && securityDatePicker.tradingCalendarData) {
                    var calendarItem = securityDatePicker.tradingCalendarData[currentDate];
                    if (calendarItem && calendarItem.weekday) {
                        // 交易日历中的weekday：1-周日，2-周一，3-周二，4-周三，5-周四，6-周五，7-周六
                        var weekdays = ['', '周日', '周一', '周二', '周三', '周四', '周五', '周六'];
                        weekday = weekdays[calendarItem.weekday];
                    }
                }
            }
            
            // 如果交易日历中没有，尝试从securityInfo中获取
            if (!weekday && securityInfo.weekday) {
                weekday = securityInfo.weekday;
            }
            
            // 如果还是没有，根据日期计算
            if (!weekday) {
                var date = securityInfo.date ? new Date(securityInfo.date) : new Date();
                var weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
                weekday = weekdays[date.getDay()];
            }
            
            $("#securityWeekday").text(weekday);
            $("#displayWeekday").text(weekday);
            
            // 计算收盘价（当天最后一个价格）
            var closePrice = null;
            if (window.currentTimeshareData && window.currentTimeshareData.length > 0) {
                // 从分时数据中获取最后一个价格作为收盘价
                var lastData = window.currentTimeshareData[window.currentTimeshareData.length - 1];
                if (lastData && lastData.length >= 2) {
                    closePrice = parseFloat(lastData[1]);
                }
            }
            
            // 显示价格信息（使用收盘价）
            if (closePrice && !isNaN(closePrice) && closePrice > 0) {
                var priceValue = closePrice.toFixed(2);
                $("#currentPrice").text(priceValue);
                $("#headerCurrentPrice").text(priceValue);
                
                // 显示涨跌幅信息（收盘价 - 昨收价）
                if (securityInfo.previousClosePrice) {
                    var prevClose = parseFloat(securityInfo.previousClosePrice);
                    var change = closePrice - prevClose;
                    var changePercent = (change / prevClose * 100).toFixed(2);
                    var changeText = (change >= 0 ? "+" : "") + change.toFixed(2) + " (" + (changePercent >= 0 ? "+" : "") + changePercent + "%)";
                    $("#priceChange").text(changeText);
                    
                    // 设置颜色
                    var color = change >= 0 ? "#e74c3c" : "#27ae60";
                    $("#currentPrice").css("color", color);
                    $("#priceChange").css("color", color);
                    $("#headerCurrentPrice").css("color", color);
                    
                    // 更新头部显示的涨跌幅信息（同一行显示）
                    var changeAmount = (change >= 0 ? "+" : "") + change.toFixed(2);
                    var changePercentText = (changePercent >= 0 ? "+" : "") + changePercent + "%";
                    $("#headerPriceChange").html(changeAmount + " (" + changePercentText + ")");
                    $("#headerPriceChange").css("color", color);
                } else {
                    $("#priceChange").text("+0.00 (+0.00%)");
                    $("#currentPrice").css("color", "#333");
                    $("#priceChange").css("color", "#333");
                    $("#headerCurrentPrice").css("color", "#333");
                    $("#headerPriceChange").html("+0.00 (+0.00%)");
                    $("#headerPriceChange").css("color", "#666");
                }
            } else {
                // 如果没有收盘价，显示N/A
                $("#currentPrice").text("N/A");
                $("#headerCurrentPrice").text("N/A");
                $("#priceChange").text("N/A");
                $("#currentPrice").css("color", "#999");
                $("#priceChange").css("color", "#999");
                $("#headerCurrentPrice").css("color", "#999");
                $("#headerPriceChange").html("N/A");
                $("#headerPriceChange").css("color", "#999");
            }
            
            // 更新其他价格信息（最高、最低、今开、昨收）
            // 先获取昨收价，用于比较
            var previousClose = null;
            if (securityInfo.previousClosePrice && !isNaN(parseFloat(securityInfo.previousClosePrice)) && parseFloat(securityInfo.previousClosePrice) > 0) {
                previousClose = parseFloat(securityInfo.previousClosePrice);
            }
            
            // 最高价（根据昨收价显示红色或绿色）
            var highestPrice = null;
            if (securityInfo.highestPrice && !isNaN(parseFloat(securityInfo.highestPrice)) && parseFloat(securityInfo.highestPrice) > 0) {
                highestPrice = parseFloat(securityInfo.highestPrice);
                if (previousClose !== null) {
                    var color = highestPrice > previousClose ? "#e74c3c" : (highestPrice < previousClose ? "#27ae60" : "#333");
                    // 计算并显示百分比，合并到价格中
                    var highestPercent = 100 * (highestPrice - previousClose) / previousClose;
                    var percentText = (highestPercent >= 0 ? "+" : "") + highestPercent.toFixed(2) + "%";
                    $("#headerHighestPrice").text(highestPrice.toFixed(2) + " (" + percentText + ")");
                    $("#headerHighestPrice").css("color", color);
                } else {
                    $("#headerHighestPrice").text(highestPrice.toFixed(2));
                    $("#headerHighestPrice").css("color", "#333");
                }
            } else {
                $("#headerHighestPrice").text("N/A");
                $("#headerHighestPrice").css("color", "#999");
            }
            
            // 最低价（根据昨收价显示红色或绿色）
            var lowestPrice = null;
            if (securityInfo.lowestPrice && !isNaN(parseFloat(securityInfo.lowestPrice)) && parseFloat(securityInfo.lowestPrice) > 0) {
                lowestPrice = parseFloat(securityInfo.lowestPrice);
                if (previousClose !== null) {
                    var color = lowestPrice > previousClose ? "#e74c3c" : (lowestPrice < previousClose ? "#27ae60" : "#333");
                    // 计算并显示百分比，合并到价格中
                    var lowestPercent = 100 * (lowestPrice - previousClose) / previousClose;
                    var percentText = (lowestPercent >= 0 ? "+" : "") + lowestPercent.toFixed(2) + "%";
                    $("#headerLowestPrice").text(lowestPrice.toFixed(2) + " (" + percentText + ")");
                    $("#headerLowestPrice").css("color", color);
                } else {
                    $("#headerLowestPrice").text(lowestPrice.toFixed(2));
                    $("#headerLowestPrice").css("color", "#333");
                }
            } else {
                $("#headerLowestPrice").text("N/A");
                $("#headerLowestPrice").css("color", "#999");
            }
            
            // 计算并显示振幅：振幅值 = 最高价 - 最低价，振幅百分比 = 100 * (最高价 - 最低价) / 昨收价
            if (highestPrice !== null && lowestPrice !== null && previousClose !== null && previousClose > 0) {
                var amplitudeValue = highestPrice - lowestPrice; // 振幅值
                var amplitudePercent = 100 * amplitudeValue / previousClose; // 振幅百分比
                var amplitudeText = amplitudeValue.toFixed(2) + " (" + amplitudePercent.toFixed(2) + "%)";
                $("#headerAmplitude").text(amplitudeText);
                $("#headerAmplitude").css("color", "#333");
            } else {
                $("#headerAmplitude").text("N/A");
                $("#headerAmplitude").css("color", "#999");
            }
            
            // 显示涨跌信息（涨跌额和涨跌幅）
            if (closePrice && !isNaN(closePrice) && closePrice > 0 && previousClose !== null && previousClose > 0) {
                var change = closePrice - previousClose;
                var changePercent = (change / previousClose * 100).toFixed(2);
                var changeAmount = (change >= 0 ? "+" : "") + change.toFixed(2);
                var changePercentText = (changePercent >= 0 ? "+" : "") + changePercent + "%";
                var riseFallText = changeAmount + " (" + changePercentText + ")";
                $("#headerRiseFall").text(riseFallText);
                var color = change >= 0 ? "#e74c3c" : "#27ae60";
                $("#headerRiseFall").css("color", color);
            } else {
                $("#headerRiseFall").text("N/A");
                $("#headerRiseFall").css("color", "#999");
            }
            
            
            // 今开价（根据昨收价显示红色或绿色）
            if (securityInfo.openPrice && !isNaN(parseFloat(securityInfo.openPrice)) && parseFloat(securityInfo.openPrice) > 0) {
                var openPrice = parseFloat(securityInfo.openPrice);
                if (previousClose !== null) {
                    var color = openPrice > previousClose ? "#e74c3c" : (openPrice < previousClose ? "#27ae60" : "#333");
                    // 计算并显示百分比，合并到价格中
                    var openPercent = 100 * (openPrice - previousClose) / previousClose;
                    var percentText = (openPercent >= 0 ? "+" : "") + openPercent.toFixed(2) + "%";
                    $("#headerOpenPrice").text(openPrice.toFixed(2) + " (" + percentText + ")");
                    $("#headerOpenPrice").css("color", color);
                } else {
                    $("#headerOpenPrice").text(openPrice.toFixed(2));
                    $("#headerOpenPrice").css("color", "#333");
                }
            } else {
                $("#headerOpenPrice").text("N/A");
                $("#headerOpenPrice").css("color", "#999");
            }
            
            // 昨收价（显示黑色）
            if (previousClose !== null) {
                $("#headerPreviousClosePrice").text(previousClose.toFixed(2));
                $("#headerPreviousClosePrice").css("color", "#000");
            } else {
                $("#headerPreviousClosePrice").text("N/A");
                $("#headerPreviousClosePrice").css("color", "#999");
            }
            
            // 更新按钮状态
            updateDateNavigationButtons();
            
            console.log("更新证券信息:", {
                symbol: securityInfo.symbol,
                code: securityInfo.code,
                name: securityInfo.name,
                date: securityInfo.date,
                weekday: securityInfo.weekday,
                previousClosePrice: securityInfo.previousClosePrice,
                openPrice: securityInfo.openPrice,
                highestPrice: securityInfo.highestPrice,
                lowestPrice: securityInfo.lowestPrice
            });
        }
    }
    
    // 显示加载状态
    function showLoading() {
        if (timeshareChart) {
            timeshareChart.showLoading();
        }
        if (volumeChart) {
            volumeChart.showLoading();
        }
    }
    
    // 隐藏加载状态
    function hideLoading() {
        if (timeshareChart) {
            timeshareChart.hideLoading();
        }
        if (volumeChart) {
            volumeChart.hideLoading();
        }
    }
    
    // 显示错误消息
    function showErrorMessage(message) {
        // 移除之前的错误消息
        $('.error-message').remove();
        
        // 创建新的错误消息
        var errorHtml = '<div class="error-message">' + message + '</div>';
        $('.chart-container').prepend(errorHtml);
        
        // 3秒后自动隐藏错误消息
        setTimeout(function() {
            $('.error-message').fadeOut();
        }, 3000);
    }
    
    // 显示成功消息
    function showSuccessMessage(message) {
        // 移除之前的消息
        $('.error-message, .success-message').remove();
        
        // 创建新的成功消息
        var successHtml = '<div class="success-message" style="text-align: center; padding: 20px; color: #28a745; background: #d4edda; border: 1px solid #c3e6cb; border-radius: 4px; margin: 20px;">' + message + '</div>';
        $('.chart-container').prepend(successHtml);
        
        // 3秒后自动隐藏成功消息
        setTimeout(function() {
            $('.success-message').fadeOut();
        }, 3000);
    }
    
    // 更新图表数据
    function updateCharts(priceData, changePercentData, averagePriceData, volumeData) {
        // 保存分时数据到全局变量，用于计算收盘价
        window.currentTimeshareData = priceData;
        updateTimeshareChart(priceData, changePercentData, averagePriceData);
        updateVolumeChart(volumeData, priceData);
        hideLoading();
    }
    
    // 生成x轴标签（根据周期决定显示时间还是日期）
    function generateXAxisLabels(priceData, period, startDate, endDate) {
        if (period === '5d') {
            // 5日线：根据日期范围和索引推断日期
            var labels = [];
            
            // 每天的分钟数（241个，从09:30到15:00）
            var minutesPerDay = 241;
            
            // 获取交易日列表
            var tradingDays = [];
            if (securityDatePicker && securityDatePicker.tradingCalendarData) {
                // 从日期选择器获取交易日列表
                var calendarData = securityDatePicker.tradingCalendarData;
                var start = new Date(startDate);
                var end = new Date(endDate);
                
                // 遍历交易日历数据
                for (var dateStr in calendarData) {
                    if (calendarData.hasOwnProperty(dateStr)) {
                        var item = calendarData[dateStr];
                        // 检查是否为交易日且在日期范围内
                        if (item && item.tradingDayFlag === 1 && dateStr >= startDate && dateStr <= endDate) {
                            tradingDays.push(dateStr);
                        }
                    }
                }
                // 按日期排序
                tradingDays.sort();
            } else {
                // 如果没有交易日历，简单按日期范围生成（假设都是交易日）
                var start = new Date(startDate);
                var end = new Date(endDate);
                for (var date = new Date(start); date <= end; date.setDate(date.getDate() + 1)) {
                    var dayOfWeek = date.getDay();
                    if (dayOfWeek >= 1 && dayOfWeek <= 5) {
                        tradingDays.push(date.toISOString().split('T')[0]);
                    }
                }
            }
            
            // 根据数据索引生成标签
            // 每天有241个数据点，中间位置约为120（241/2 ≈ 120）
            var middleIndex = Math.floor(minutesPerDay / 2);
            var dayIndex = 0;
            var minuteIndex = 0;
            var lastDateLabel = '';
            
            console.log("生成5日线标签，交易日数量:", tradingDays.length, "数据点数量:", priceData.length, "中间位置索引:", middleIndex);
            
            for (var i = 0; i < priceData.length; i++) {
                if (minuteIndex === middleIndex && dayIndex < tradingDays.length) {
                    // 每天中间位置的数据点，显示日期
                    var dateStr = tradingDays[dayIndex];
                    var date = new Date(dateStr);
                    var month = String(date.getMonth() + 1).padStart(2, '0');
                    var day = String(date.getDate()).padStart(2, '0');
                    var dateLabel = month + '-' + day;
                    labels.push(dateLabel);
                    lastDateLabel = dateLabel;
                    console.log("添加日期标签:", dateLabel, "索引:", i, "dayIndex:", dayIndex, "minuteIndex:", minuteIndex);
                } else {
                    labels.push(''); // 其他时间点不显示标签
                }
                
                minuteIndex++;
                if (minuteIndex >= minutesPerDay) {
                    // 一天结束，移动到下一天
                    minuteIndex = 0;
                    dayIndex++;
                }
            }
            
            console.log("生成的标签数组长度:", labels.length, "非空标签数量:", labels.filter(function(l) { return l !== ''; }).length);
            return labels;
        } else {
            // 日线：显示时间
            return priceData.map(item => item[0]);
        }
    }
    
    // 配置分时图
    function updateTimeshareChart(priceData, changePercentData, averagePriceData) {
        if (!timeshareChart || !priceData) return;
        
        // 如果是5日线，使用专门的配置
        if (currentPeriod === '5d') {
            updateFiveDayChart(priceData, changePercentData, averagePriceData);
            return;
        }
        
        // 如果是5日线，使用专门的配置
        if (currentPeriod === '5d') {
            updateFiveDayChart(priceData, changePercentData, averagePriceData);
            return;
        }
        
        // 日线配置（原有逻辑）
        // 获取昨收价作为基准线
        var previousClosePrice = 0;
        if (window.currentSecurityInfo && window.currentSecurityInfo.previousClosePrice) {
            previousClosePrice = parseFloat(window.currentSecurityInfo.previousClosePrice);
        }
        
        // 从接口获取最大价格和最小价格
        var minPrice = 0;
        var maxPrice = 0;
        var priceRange = 0;
        var centerPrice = 0;
        
        if (window.currentSecurityInfo) {
            // 从接口数据获取价格信息
            minPrice = parseFloat(window.currentSecurityInfo.lowestPrice || 0);
            maxPrice = parseFloat(window.currentSecurityInfo.highestPrice || 0);
            priceRange = maxPrice - minPrice;
            centerPrice = previousClosePrice > 0 ? previousClosePrice : (minPrice + maxPrice) / 2;
        } else {
            // 如果没有接口数据，使用原来的计算逻辑作为备用
            var prices = priceData.map(item => parseFloat(item[1]));
            minPrice = Math.min(...prices);
            maxPrice = Math.max(...prices);
            priceRange = maxPrice - minPrice;
            centerPrice = previousClosePrice > 0 ? previousClosePrice : (minPrice + maxPrice) / 2;
        }
        
        // 设置Y轴范围，以昨收价为水平线，上方和下方各4格
        var yAxisMin, yAxisMax;
        if (previousClosePrice > 0 && window.currentSecurityInfo && minPrice > 0 && maxPrice > 0) {
            // 根据接口返回的最高价和最低价计算最大涨跌幅
            var maxRisePercent = ((maxPrice - previousClosePrice) / previousClosePrice) * 100;
            var maxFallPercent = ((minPrice - previousClosePrice) / previousClosePrice) * 100;
            var maxPercent = Math.max(Math.abs(maxRisePercent), Math.abs(maxFallPercent));
            
            // 计算Y轴范围：昨收价为中心，上下各maxPercent%
            yAxisMax = previousClosePrice * (1 + maxPercent / 100);
            yAxisMin = previousClosePrice * (1 - maxPercent / 100);
        } else {
            // 如果没有昨收价或接口数据，使用原来的逻辑
            yAxisMin = centerPrice - priceRange * 0.5;
            yAxisMax = centerPrice + priceRange * 0.5;
        }
        
        const option = {
            backgroundColor: 'transparent', // 图表背景透明
            title: {
                show: false // 隐藏标题，让图表更简洁
            },
            legend: {
                show: false // 隐藏图例，让图表更简洁
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    lineStyle: {
                        color: 'rgba(0, 0, 0, 0.15)', // 更淡的颜色
                        width: 1,
                        type: 'dashed',
                        lineDash: [10, 8] // 虚线点间隔：10px实线，8px空白
                    },
                    label: {
                        show: false // 隐藏axisPointer上的数值标签
                    }
                },
                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                borderColor: '#ccc',
                borderWidth: 1,
                textStyle: {
                    color: '#fff',
                    fontSize: 12
                },
                formatter: function(params) {
                    var result = `时间: ${params[0].axisValue}<br/>`;
                    params.forEach(function(param) {
                        if (param.seriesName === '证券价格') {
                            result += `价格: ${param.value}<br/>`;
                        } else if (param.seriesName === '涨跌幅') {
                            result += `涨跌幅: ${param.value}%<br/>`;
                        } else if (param.seriesName === '均价线') {
                            result += `均价: ${param.value}<br/>`;
                        }
                    });
                    return result;
                }
            },
            grid: {
                left: '4%',
                right: '4%',
                bottom: '5%', // 减少底部边距，显示更多图表
                top: '5%',
                containLabel: true,
                backgroundColor: 'transparent' // 确保网格背景透明
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: generateXAxisLabels(priceData, currentPeriod, window.currentStartDate, window.currentEndDate),
                axisLine: {
                    show: false // 隐藏轴线
                },
                axisTick: {
                    show: false // 隐藏刻度线
                },
                axisLabel: {
                    color: '#666',
                    fontSize: 11,
                    rotate: 0, // 横向显示
                    interval: function(index, value) {
                        if (currentPeriod === '5d') {
                            // 5日线：只显示有值的标签（日期）
                            return value === '' || value === undefined;
                        } else {
                            // 日线：30分钟间隔显示
                            return index % 30 === 0;
                        }
                    },
                    formatter: function(value) {
                        if (currentPeriod === '5d' && value) {
                            // 5日线：显示日期（已经是格式化后的）
                            return value;
                        }
                        return value;
                    }
                },
                splitLine: {
                    show: currentPeriod === '1d', // 日线显示分割线，5日线不显示
                    lineStyle: {
                        color: '#ddd', // 浅灰色
                        type: 'dashed', // 虚线
                        width: 1
                    },
                    interval: function(index, value) {
                        if (currentPeriod === '1d') {
                            // 日线：只在整点和半点显示分割线（09:30, 10:00, 10:30, 11:00, 11:30, 13:00, 13:30, 14:00, 14:30, 15:00）
                            // interval返回true表示显示分割线，返回false表示不显示
                            if (value && typeof value === 'string') {
                                // 检查时间格式是否为HH:mm，且分钟为00或30
                                var timeMatch = value.match(/^(\d{2}):(\d{2})$/);
                                if (timeMatch) {
                                    var minutes = timeMatch[2];
                                    // 只在整点（00）或半点（30）显示分割线
                                    if (minutes === '00' || minutes === '30') {
                                        return true; // 显示分割线
                                    }
                                }
                            }
                            return false; // 其他时间点不显示分割线
                        }
                        return false; // 5日线不显示分割线
                    }
                }
            },
            yAxis: [
                {
                    type: 'value',
                    min: yAxisMin,
                    max: yAxisMax,
                    splitNumber: 8, // 分为8个区间，总共9个刻度点
                    position: 'left',
                    // 使用自定义刻度，确保等分效果
                    interval: previousClosePrice > 0 ? (yAxisMax - yAxisMin) / 8 : null,
                    axisLine: {
                        show: false // 隐藏轴线
                    },
                    axisTick: {
                        show: false // 隐藏刻度线
                    },
                    axisLabel: {
                        color: '#666',
                        fontSize: 11,
                        formatter: function(value) {
                            // 确保所有数值都显示两位小数
                            var formattedValue = parseFloat(value).toFixed(2);
                            
                            // 根据价格与昨收价的关系设置颜色
                            if (previousClosePrice > 0) {
                                // 使用容差判断是否相等，避免浮点数精度问题
                                var tolerance = 0.01; // 1分钱的容差
                                if (Math.abs(value - previousClosePrice) < tolerance) {
                                    return '{black|' + formattedValue + '}';
                                } else if (value > previousClosePrice) {
                                    return '{red|' + formattedValue + '}';
                                } else {
                                    return '{green|' + formattedValue + '}';
                                }
                            }
                            return formattedValue;
                        },
                        rich: {
                            red: {
                                color: '#e74c3c'
                            },
                            green: {
                                color: '#27ae60'
                            },
                            black: {
                                color: '#333'
                            }
                        }
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: '#fafafa',
                            width: 1,
                            type: 'solid'
                        }
                    }
                },
                {
                    type: 'value',
                    min: previousClosePrice > 0 ? (yAxisMin - previousClosePrice) / previousClosePrice * 100 : null,
                    max: previousClosePrice > 0 ? (yAxisMax - previousClosePrice) / previousClosePrice * 100 : null,
                    splitNumber: 8, // 分为8个区间，总共9个刻度点
                    position: 'right',
                    show: true, // 确保右边Y轴显示
                    // 使用自定义刻度，确保等分效果
                    interval: previousClosePrice > 0 ? ((yAxisMax - previousClosePrice) / previousClosePrice * 100) / 4 : null,
                    axisLine: {
                        show: false // 隐藏轴线
                    },
                    axisTick: {
                        show: false // 隐藏刻度线
                    },
                    axisLabel: {
                        show: true, // 确保标签显示
                        color: '#666',
                        fontSize: 11,
                        formatter: function(value) {
                            // 确保所有数值都显示两位小数
                            var formattedValue = parseFloat(value).toFixed(2);
                            
                            // 根据涨跌幅设置颜色
                            if (Math.abs(value) < 0.01) { // 0%线
                                return '{black|0.00%}';
                            } else if (value > 0) {
                                return '{red|+' + formattedValue + '%}';
                            } else {
                                return '{green|' + formattedValue + '%}';
                            }
                        },
                        rich: {
                            red: {
                                color: '#e74c3c'
                            },
                            green: {
                                color: '#27ae60'
                            },
                            black: {
                                color: '#333'
                            }
                        }
                    },
                    splitLine: {
                        show: false
                    }
                }
            ],
            dataZoom: [
                {
                    type: 'inside',
                    start: 0,
                    end: 100
                },
                {
                    type: 'slider',
                    show: true,
                    bottom: '2%', // 滑块更靠近底部
                    start: 0,
                    end: 100,
                    height: 15 // 减小滑块高度
                }
            ],
            series: [
                {
                    name: '证券价格',
                    type: 'line',
                    yAxisIndex: 0,
                    data: priceData.map(item => item[1]),
                    smooth: true,
                    symbol: 'none', // 去掉数据点的圆圈
                    lineStyle: {
                        color: '#1565C0', // 更深的蓝色
                        width: 1 // 更细的线条
                    },
                    itemStyle: {
                        color: '#1565C0'
                    }
                },
                {
                    name: '均价线',
                    type: 'line',
                    yAxisIndex: 0,
                    data: averagePriceData ? averagePriceData.map(item => item[1]) : [],
                    smooth: true,
                    symbol: 'none',
                    lineStyle: {
                        color: '#FFA000', // 更深的黄色
                        width: 1,
                        type: 'solid'
                    },
                    itemStyle: {
                        color: '#FFA000'
                    }
                }
            ]
        };
        
        // 如果有昨收价，添加基准线（0%线）
        if (previousClosePrice > 0) {
            option.series.push({
                name: '昨收价',
                type: 'line',
                yAxisIndex: 0,
                data: priceData.map(() => previousClosePrice),
                lineStyle: {
                    color: '#333333', // 黑色虚线
                    width: 1,
                    type: 'dashed'
                },
                itemStyle: {
                    color: '#333333'
                },
                symbol: 'none',
                silent: true
            });
        }
        
        // 使用notMerge: true确保完全替换配置，清除之前的滚动轴
        timeshareChart.setOption(option, true);
    }
    
    // 配置5日线图表
    function updateFiveDayChart(priceData, changePercentData, averagePriceData) {
        if (!timeshareChart || !priceData) return;
        
        // 获取昨收价（使用第一个交易日的昨收价）
        var previousClosePrice = 0;
        if (window.currentSecurityInfo && window.currentSecurityInfo.previousClosePrice) {
            previousClosePrice = parseFloat(window.currentSecurityInfo.previousClosePrice);
        }
        
        // 计算价格范围
        var prices = priceData.map(item => parseFloat(item[1]));
        var minPrice = Math.min(...prices);
        var maxPrice = Math.max(...prices);
        var priceRange = maxPrice - minPrice;
        
        // 计算Y轴范围
        var yAxisMin, yAxisMax;
        if (previousClosePrice > 0) {
            var maxRisePercent = ((maxPrice - previousClosePrice) / previousClosePrice) * 100;
            var maxFallPercent = ((minPrice - previousClosePrice) / previousClosePrice) * 100;
            var maxPercent = Math.max(Math.abs(maxRisePercent), Math.abs(maxFallPercent));
            yAxisMax = previousClosePrice * (1 + maxPercent / 100 * 1.1); // 增加10%的边距
            yAxisMin = previousClosePrice * (1 - maxPercent / 100 * 1.1);
        } else {
            yAxisMin = minPrice - priceRange * 0.1;
            yAxisMax = maxPrice + priceRange * 0.1;
        }
        
        // 生成x轴标签和日期分隔线位置
        var xAxisLabels = generateXAxisLabels(priceData, currentPeriod, window.currentStartDate, window.currentEndDate);
        console.log("5日线X轴标签:", xAxisLabels);
        console.log("日期范围:", window.currentStartDate, window.currentEndDate);
        var minutesPerDay = 241;
        var markLineData = [];
        var tradingDays = [];
        
        // 获取交易日列表
        if (securityDatePicker && securityDatePicker.tradingCalendarData) {
            var calendarData = securityDatePicker.tradingCalendarData;
            for (var dateStr in calendarData) {
                if (calendarData.hasOwnProperty(dateStr)) {
                    var item = calendarData[dateStr];
                    if (item && item.tradingDayFlag === 1 && dateStr >= window.currentStartDate && dateStr <= window.currentEndDate) {
                        tradingDays.push(dateStr);
                    }
                }
            }
            tradingDays.sort();
        }
        
        // 生成日期分隔线（每天的开始位置）
        for (var i = 1; i < tradingDays.length; i++) {
            markLineData.push({
                xAxis: i * minutesPerDay - 0.5
            });
        }
        
        // 生成tooltip数据映射（日期+时间）
        var tooltipDataMap = [];
        var dayIndex = 0;
        var minuteIndex = 0;
        for (var i = 0; i < priceData.length; i++) {
            var dateStr = '';
            var timeStr = priceData[i][0];
            if (dayIndex < tradingDays.length) {
                dateStr = tradingDays[dayIndex];
                var date = new Date(dateStr);
                var month = String(date.getMonth() + 1).padStart(2, '0');
                var day = String(date.getDate()).padStart(2, '0');
                dateStr = month + '-' + day;
            }
            tooltipDataMap.push({
                date: dateStr,
                time: timeStr,
                index: i
            });
            
            minuteIndex++;
            if (minuteIndex >= minutesPerDay) {
                minuteIndex = 0;
                dayIndex++;
            }
        }
        
        const option = {
            backgroundColor: 'transparent', // 图表背景透明
            title: {
                show: false
            },
            legend: {
                show: false
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    lineStyle: {
                        color: 'rgba(0, 0, 0, 0.15)',
                        width: 1,
                        type: 'dashed',
                        lineDash: [10, 8]
                    },
                    label: {
                        show: false // 隐藏axisPointer上的数值标签
                    }
                },
                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                borderColor: '#ccc',
                borderWidth: 1,
                textStyle: {
                    color: '#fff',
                    fontSize: 12
                },
                formatter: function(params) {
                    var dataIndex = params[0].dataIndex;
                    var tooltipInfo = tooltipDataMap[dataIndex];
                    var result = '';
                    if (tooltipInfo && tooltipInfo.date) {
                        result = `日期: ${tooltipInfo.date} ${tooltipInfo.time}<br/>`;
                    } else {
                        result = `时间: ${params[0].axisValue}<br/>`;
                    }
                    params.forEach(function(param) {
                        if (param.seriesName === '证券价格') {
                            result += `价格: ${param.value}<br/>`;
                        } else if (param.seriesName === '涨跌幅') {
                            result += `涨跌幅: ${param.value}%<br/>`;
                        } else if (param.seriesName === '均价线') {
                            result += `均价: ${param.value}<br/>`;
                        }
                    });
                    return result;
                }
            },
            grid: {
                left: '4%',
                right: '4%',
                bottom: '8%', // 增加底部边距，为X轴日期标签留出空间
                top: '5%',
                containLabel: true,
                backgroundColor: 'transparent' // 确保网格背景透明
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: xAxisLabels,
                axisLine: {
                    show: false
                },
                axisTick: {
                    show: false
                },
                axisLabel: {
                    color: '#666',
                    fontSize: 11,
                    rotate: 0, // 横向显示
                    interval: 0, // 显示所有标签
                    margin: 8, // 增加标签与轴线的距离
                    formatter: function(value, index) {
                        // 只显示有值的标签（日期），空值返回空字符串
                        if (value && value !== '' && value !== undefined && value !== null) {
                            return value;
                        }
                        return '';
                    }
                },
                splitLine: {
                    show: true, // 显示日分隔线
                    lineStyle: {
                        color: '#ddd', // 浅灰色
                        type: 'dashed', // 虚线
                        width: 1
                    },
                    interval: function(index) {
                        // 在每天的开始位置显示分隔线
                        return index % minutesPerDay === 0;
                    }
                }
            },
            yAxis: [
                {
                    type: 'value',
                    min: yAxisMin,
                    max: yAxisMax,
                    splitNumber: 8,
                    position: 'left',
                    interval: previousClosePrice > 0 ? (yAxisMax - yAxisMin) / 8 : null,
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        color: '#666',
                        fontSize: 11,
                        formatter: function(value) {
                            var formattedValue = parseFloat(value).toFixed(2);
                            if (previousClosePrice > 0) {
                                var tolerance = 0.01;
                                if (Math.abs(value - previousClosePrice) < tolerance) {
                                    return '{black|' + formattedValue + '}';
                                } else if (value > previousClosePrice) {
                                    return '{red|' + formattedValue + '}';
                                } else {
                                    return '{green|' + formattedValue + '}';
                                }
                            }
                            return formattedValue;
                        },
                        rich: {
                            red: {
                                color: '#e74c3c'
                            },
                            green: {
                                color: '#27ae60'
                            },
                            black: {
                                color: '#333333'
                            }
                        }
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: '#eee',
                            type: 'dashed'
                        }
                    }
                },
                {
                    type: 'value',
                    position: 'right',
                    show: true, // 确保右边Y轴显示
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        show: true, // 确保标签显示
                        color: '#666',
                        fontSize: 11,
                        formatter: function(value) {
                            var formattedValue = parseFloat(value).toFixed(2);
                            if (Math.abs(value) < 0.01) {
                                return '{black|0.00%}';
                            } else if (value > 0) {
                                return '{red|+' + formattedValue + '%}';
                            } else {
                                return '{green|' + formattedValue + '%}';
                            }
                        },
                        rich: {
                            red: {
                                color: '#e74c3c'
                            },
                            green: {
                                color: '#27ae60'
                            },
                            black: {
                                color: '#333333'
                            }
                        }
                    },
                    splitLine: {
                        show: false
                    }
                }
            ],
            dataZoom: [
                {
                    type: 'inside',
                    start: 0,
                    end: 100
                },
                {
                    type: 'slider',
                    show: true,
                    bottom: '2%', // 滑块更靠近底部
                    start: 0,
                    end: 100,
                    height: 15 // 减小滑块高度
                }
            ],
            series: [
                {
                    name: '证券价格',
                    type: 'line',
                    yAxisIndex: 0,
                    data: priceData.map(item => item[1]),
                    smooth: false,
                    symbol: 'none',
                    lineStyle: {
                        color: '#1f77b4',
                        width: 1 // 更细的线条
                    },
                    itemStyle: {
                        color: '#1f77b4'
                    },
                    markLine: markLineData.length > 0 ? {
                        data: markLineData,
                        silent: true,
                        animation: false,
                        symbol: 'none', // 隐藏箭头
                        symbolSize: 0, // 箭头大小为0
                        lineStyle: {
                            color: '#ddd',
                            type: 'dashed',
                            width: 1
                        },
                        label: {
                            show: false // 隐藏标签
                        }
                    } : undefined
                },
                {
                    name: '均价线',
                    type: 'line',
                    yAxisIndex: 0,
                    data: averagePriceData ? averagePriceData.map(item => item[1]) : [],
                    smooth: false,
                    symbol: 'none',
                    lineStyle: {
                        color: '#FFA000', // 更深的黄色
                        width: 1,
                        type: 'solid'
                    },
                    itemStyle: {
                        color: '#FFA000'
                    }
                }
            ]
        };
        
        // 如果有昨收价，添加基准线
        if (previousClosePrice > 0) {
            option.series.push({
                name: '昨收价',
                type: 'line',
                yAxisIndex: 0,
                data: priceData.map(() => previousClosePrice),
                lineStyle: {
                    color: '#333333',
                    width: 1,
                    type: 'dashed'
                },
                itemStyle: {
                    color: '#333333'
                },
                symbol: 'none',
                silent: true
            });
        }
        
        timeshareChart.setOption(option);
    }
    
    // 根据成交量大小动态确定单位和除数
    function getVolumeUnit(maxVolume) {
        if (maxVolume >= 100000000) {
            // 大于等于1亿，使用"亿手"
            return { unit: '亿手', divisor: 100000000 };
        } else if (maxVolume >= 10000000) {
            // 大于等于1千万，使用"千万手"
            return { unit: '千万手', divisor: 10000000 };
        } else if (maxVolume >= 10000) {
            // 大于等于1万，使用"万手"
            return { unit: '万手', divisor: 10000 };
        } else {
            // 小于1万，使用"手"
            return { unit: '手', divisor: 1 };
        }
    }
    
    // 配置成交量图
    function updateVolumeChart(volumeData, priceData) {
        if (!volumeChart || !volumeData) return;
        
        // 计算最大成交量，用于动态确定单位
        var maxVolume = Math.max.apply(Math, volumeData.map(item => item[1]));
        
        // 根据最大成交量动态确定单位和除数
        var unitInfo = getVolumeUnit(maxVolume);
        
        // 获取昨收价作为基准
        var previousClosePrice = 0;
        if (window.currentSecurityInfo && window.currentSecurityInfo.previousClosePrice) {
            previousClosePrice = parseFloat(window.currentSecurityInfo.previousClosePrice);
        }
        
        // 创建价格映射表，便于快速查找
        var priceMap = {};
        if (priceData && priceData.length > 0) {
            priceData.forEach(function(item) {
                priceMap[item[0]] = parseFloat(item[1]);
            });
        }
        
        // 预计算每个成交量柱的颜色
        var volumeColors = [];
        volumeData.forEach(function(item, index) {
            var time = item[0];
            var color = '#999999'; // 默认灰色
            
            if (priceData && priceData.length > 0) {
                var currentPrice = priceMap[time];
                
                if (currentPrice !== null && currentPrice !== undefined) {
                    var prevPrice = null;
                    
                    // 查找前一个时间点的价格
                    if (index > 0) {
                        var prevTime = volumeData[index - 1][0];
                        prevPrice = priceMap[prevTime];
                    }
                    
                    // 如果没有前一个价格，使用昨收价作为基准
                    if (prevPrice === null || prevPrice === undefined) {
                        prevPrice = previousClosePrice;
                    }
                    
                    // 根据价格变化设置颜色
                    if (prevPrice !== null && prevPrice !== undefined) {
                        if (currentPrice > prevPrice) {
                            color = '#e74c3c'; // 红色：价格上涨
                        } else if (currentPrice < prevPrice) {
                            color = '#27ae60'; // 绿色：价格下跌
                        } else {
                            color = '#999999'; // 灰色：价格不变
                        }
                    } else if (previousClosePrice > 0) {
                        // 如果没有前一个价格，但与昨收价比较
                        if (currentPrice > previousClosePrice) {
                            color = '#e74c3c'; // 红色
                        } else if (currentPrice < previousClosePrice) {
                            color = '#27ae60'; // 绿色
                        }
                    }
                }
            }
            
            volumeColors.push(color);
        });
        
        const option = {
            title: {
                show: false // 隐藏标题
            },
            tooltip: {
                trigger: 'axis',
                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                borderColor: '#ccc',
                borderWidth: 1,
                textStyle: {
                    color: '#fff',
                    fontSize: 12
                },
                formatter: function(params) {
                    const data = params[0];
                    var displayValue = (data.value / unitInfo.divisor).toFixed(2);
                    return `时间: ${data.axisValue}<br/>成交量: ${displayValue}${unitInfo.unit}`;
                }
            },
            grid: {
                left: '4%',
                right: '4%',
                bottom: '5%',
                top: '5%',
                containLabel: true,
                backgroundColor: 'transparent' // 确保网格背景透明
            },
            xAxis: {
                type: 'category',
                data: (function() {
                    // 根据周期生成x轴标签（成交量图使用相同的x轴）
                    if (currentPeriod === '5d') {
                        // 5日线：使用相同的日期生成逻辑
                        return generateXAxisLabels(priceData, currentPeriod, window.currentStartDate, window.currentEndDate);
                    } else {
                        // 日线：显示时间
                        return volumeData.map(item => item[0]);
                    }
                })(),
                axisLine: {
                    show: false // 隐藏轴线
                },
                axisTick: {
                    show: false // 隐藏刻度线
                },
                axisLabel: {
                    color: '#666',
                    fontSize: 11,
                    rotate: 0, // 横向显示
                    interval: function(index, value) {
                        if (currentPeriod === '5d') {
                            // 5日线：只显示有值的标签（日期）
                            return value === '' || value === undefined;
                        } else {
                            // 日线：30分钟间隔显示
                            return index % 30 === 0;
                        }
                    },
                    formatter: function(value) {
                        if (currentPeriod === '5d' && value) {
                            // 5日线：显示日期
                            return value;
                        }
                        return value;
                    }
                },
                splitLine: {
                    show: false // 隐藏分割线
                }
            },
            yAxis: {
                type: 'value',
                axisLine: {
                    show: false // 隐藏轴线
                },
                axisTick: {
                    show: false // 隐藏刻度线
                },
                axisLabel: {
                    color: '#666',
                    fontSize: 11,
                    formatter: function(value) {
                        var displayValue = (value / unitInfo.divisor).toFixed(0);
                        return displayValue + unitInfo.unit;
                    }
                },
                splitLine: {
                    show: false // 隐藏分割线
                }
            },
            series: [{
                name: '成交量',
                type: 'bar',
                data: volumeData.map(item => item[1]),
                barWidth: '60%', // 设置柱状图宽度
                itemStyle: {
                    color: function(params) {
                        // 根据数据索引返回对应的颜色
                        var index = params.dataIndex;
                        return volumeColors[index] || '#999999';
                    }
                }
            }]
        };
        
        volumeChart.setOption(option);
    }
    
    
    // 切换时间周期
    function switchPeriod(period, event) {
        // 阻止默认行为和事件冒泡
        if (event) {
            event.preventDefault();
            event.stopPropagation();
        }
        
        // 更新按钮状态
        $('.period-buttons .btn').removeClass('active');
        if (event && event.target) {
            $(event.target).addClass('active');
        } else {
            // 如果没有event对象，根据period找到对应的按钮
            $('.period-buttons .btn').each(function() {
                var btn = $(this);
                if (btn.text().trim() === (period === '1d' ? '日线' : '5日线')) {
                    btn.addClass('active');
                }
            });
        }
        
        // 更新当前周期
        currentPeriod = period;
        
        // 重新加载数据（不会清空输入框，只是重新请求数据）
        loadSecurityData();
    }
    
    // 根据结束日期和时间周期计算开始日期
    function calculateStartDate(endDate, period) {
        var end = new Date(endDate);
        
        switch(period) {
            case '1d':
                // 日线：开始日期和结束日期相同
                return endDate;
                
            case '5d':
                // 5日线：开始日期为前面5个交易日
                return getPreviousTradingDays(endDate, 5);
                
            default:
                return endDate;
        }
    }
    
    // 获取前面N个交易日的日期
    function getPreviousTradingDays(endDate, tradingDays) {
        // 如果日期选择组件存在，使用组件的交易日历数据
        if (securityDatePicker && Object.keys(securityDatePicker.tradingCalendarData).length > 0) {
            // 遍历交易日历，按日期倒序，过滤出交易日
            var tradingDaysList = [];
            for (var dateStr in securityDatePicker.tradingCalendarData) {
                var item = securityDatePicker.tradingCalendarData[dateStr];
                if (item && item.tradingDayFlag === 1 && dateStr <= endDate) {
                    tradingDaysList.push(dateStr);
                }
            }
            
            // 按日期倒序排列
            tradingDaysList.sort().reverse();
            
            // 取第N个交易日作为开始日期
            if (tradingDaysList.length >= tradingDays) {
                return tradingDaysList[tradingDays - 1];
            }
        }
        
        // 如果交易日历数据未加载或数据不足，使用简单逻辑
        var date = new Date(endDate);
        var count = 0;
        
        while (count < tradingDays) {
            date.setDate(date.getDate() - 1);
            var dayOfWeek = date.getDay();
            
            // 如果是工作日（周一到周五），计数加1
            if (dayOfWeek >= 1 && dayOfWeek <= 5) {
                count++;
            }
        }
        
        var year = date.getFullYear();
        var month = String(date.getMonth() + 1).padStart(2, '0');
        var day = String(date.getDate()).padStart(2, '0');
        return year + '-' + month + '-' + day;
    }
    
    // 重置表单
    function resetForm() {
        // 重置为默认上证指数
        if (securitySelector) {
            var defaultSecurity = securitySelector.securitiesList.find(function(security) {
                return security.symbol === "sh000001";
            });
            if (defaultSecurity) {
                securitySelector.setSelectedSecurity(defaultSecurity);
                // 更新显示信息
                $("#displayCode").text(defaultSecurity.code);
                $("#displayName").text(defaultSecurity.name);
            }
        } else {
            $("#securitySelect").val("sh000001 - 上证指数");
            $("#securitySymbol").val("sh000001");
        }
        
        currentSecuritySymbol = "sh000001"; // 重置为默认上证指数
        currentPeriod = "1d"; // 重置为日线
        
        // 重置日期选择框为今天
        if (securityDatePicker) {
            var today = new Date();
            var todayStr = today.toISOString().split('T')[0];
            securityDatePicker.setDate(todayStr);
        }
        
        // 隐藏下拉框
        if (securitySelector) {
            securitySelector.hideDropdown();
        }
        
        // 重置按钮状态
        $('.period-buttons .btn').removeClass('active');
        $('.period-buttons .btn:first').addClass('active'); // 激活日线按钮
        
        // 重新加载默认数据
        loadSecurityData();
    }
    
    // 同步分时数据相关的变量
    var syncTimeshareStartDatePicker = null;
    var syncTimeshareEndDatePicker = null;
    var syncTimeshareTimer = null; // 进度轮询定时器
    var syncTimeshareStartTime = null;
    var syncTimeshareTaskId = null; // 同步任务ID
    var syncTimeshareTotalDays = 0; // 总天数
    var syncTimeshareSyncedDays = 0; // 已同步天数
    var syncTimeshareLastTimeUpdate = 0; // 上次更新时间（用于控制预计时间和剩余时间更新频率）
    
    // 显示同步分时数据模态框
    function showSyncTimeshareModal() {
        // 检查是否选择了证券
        var symbol = currentSecuritySymbol;
        if (!symbol || symbol.trim() === "") {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        
        // 隐藏进度条
        $("#syncTimeshareProgress").css("display", "none");
        
        // 显示模态框
        $("#syncTimeshareModal").css("display", "flex");
        
        // 重置所有快捷按钮的高亮状态（先清除之前的高亮）
        $(".sync-quick-date-btn").css({
            "background": "#f5f5f5",
            "color": "#666",
            "border-color": "#ddd"
        });
        
        // 计算当前时间和最大可选日期
        var now = new Date();
        var currentHour = now.getHours();
        var currentMinute = now.getMinutes();
        var isAfter1500 = (currentHour > 15) || (currentHour === 15 && currentMinute >= 0);
        
        // 如果当前时间大于15:00，最大可选日期为今天；否则为昨天
        var maxDate = null;
        if (isAfter1500) {
            maxDate = new Date(now);
        } else {
            var yesterday = new Date(now);
            yesterday.setDate(yesterday.getDate() - 1);
            maxDate = yesterday;
        }
        
        // 计算默认日期（当日）
        var todayStr = now.toISOString().split('T')[0];
        var defaultStartDate;
        var defaultEndDate;
        
        if (isAfter1500) {
            // 当前时间大于15:00，默认选择当日
            defaultStartDate = todayStr;
            defaultEndDate = todayStr;
        } else {
            // 当前时间小于等于15:00，默认选择前一个交易日
            var yesterday = new Date(now);
            yesterday.setDate(yesterday.getDate() - 1);
            var yesterdayStr = yesterday.toISOString().split('T')[0];
            defaultStartDate = yesterdayStr;
            defaultEndDate = yesterdayStr;
        }
        
        // 更新"当日"按钮的禁用状态
        var todayButton = $('.sync-quick-date-btn[data-days="0"]');
        if (isAfter1500) {
            todayButton.prop('disabled', false).css({
                'background': '#f5f5f5',
                'color': '#666',
                'cursor': 'pointer',
                'opacity': '1'
            });
        } else {
            todayButton.prop('disabled', true).css({
                'background': '#e0e0e0',
                'color': '#999',
                'cursor': 'not-allowed',
                'opacity': '0.6'
            });
        }
        
        // 初始化日期选择器（延迟执行，确保DOM已渲染）
        setTimeout(function() {
            // 初始化开始日期选择器
            if (!syncTimeshareStartDatePicker) {
                syncTimeshareStartDatePicker = new SecurityDatePicker({
                    inputId: 'syncTimeshareStartDate',
                    calendarId: 'syncTimeshareStartDateCalendar',
                    apiPrefix: prefix,
                    maxDate: maxDate,
                    autoInitDate: false,
                    onDateSelect: function(date) {
                        console.log('开始日期选择:', date);
                    }
                });
                syncTimeshareStartDatePicker.init();
            } else {
                // 更新已有选择器的maxDate
                syncTimeshareStartDatePicker.options.maxDate = maxDate;
            }
            
            // 初始化结束日期选择器
            if (!syncTimeshareEndDatePicker) {
                syncTimeshareEndDatePicker = new SecurityDatePicker({
                    inputId: 'syncTimeshareEndDate',
                    calendarId: 'syncTimeshareEndDateCalendar',
                    apiPrefix: prefix,
                    maxDate: maxDate,
                    autoInitDate: false,
                    onDateSelect: function(date) {
                        console.log('结束日期选择:', date);
                    }
                });
                syncTimeshareEndDatePicker.init();
            } else {
                // 更新已有选择器的maxDate
                syncTimeshareEndDatePicker.options.maxDate = maxDate;
            }
            
            // 复用已有日期选择器的交易日历数据
            if (securityDatePicker && securityDatePicker.tradingCalendarData) {
                syncTimeshareStartDatePicker.tradingCalendarData = $.extend({}, securityDatePicker.tradingCalendarData);
                syncTimeshareEndDatePicker.tradingCalendarData = $.extend({}, securityDatePicker.tradingCalendarData);
            }
            
            // 设置默认日期
            var nearestStartDate;
            var nearestEndDate;
            
            if (isAfter1500) {
                // 当前时间大于15:00，默认选择当日
                nearestStartDate = syncTimeshareStartDatePicker.findNearestTradingDay ? 
                    syncTimeshareStartDatePicker.findNearestTradingDay(defaultStartDate) : defaultStartDate;
                nearestEndDate = syncTimeshareEndDatePicker.findNearestTradingDay ? 
                    syncTimeshareEndDatePicker.findNearestTradingDay(defaultEndDate) : defaultEndDate;
            } else {
                // 当前时间小于等于15:00，默认选择前一个交易日
                nearestStartDate = syncTimeshareStartDatePicker.findPreviousTradingDay ? 
                    syncTimeshareStartDatePicker.findPreviousTradingDay(todayStr) : defaultStartDate;
                if (!nearestStartDate || nearestStartDate === todayStr) {
                    nearestStartDate = syncTimeshareStartDatePicker.findNearestTradingDay ? 
                        syncTimeshareStartDatePicker.findNearestTradingDay(defaultStartDate) : defaultStartDate;
                }
                
                nearestEndDate = syncTimeshareEndDatePicker.findPreviousTradingDay ? 
                    syncTimeshareEndDatePicker.findPreviousTradingDay(todayStr) : defaultEndDate;
                if (!nearestEndDate || nearestEndDate === todayStr) {
                    nearestEndDate = syncTimeshareEndDatePicker.findNearestTradingDay ? 
                        syncTimeshareEndDatePicker.findNearestTradingDay(defaultEndDate) : defaultEndDate;
                }
            }
            
            syncTimeshareStartDatePicker.setDate(nearestStartDate);
            syncTimeshareEndDatePicker.setDate(nearestEndDate);
            
            // 根据设置的默认日期高亮对应的快捷按钮
            // 默认情况下，应该高亮"当日"按钮（如果当前时间大于15:00）
            // 因为默认日期就是当日
            if (isAfter1500) {
                // 当前时间大于15:00，默认选择当日，高亮"当日"按钮
                $('.sync-quick-date-btn[data-days="0"]').css({
                    "background": "#007bff",
                    "color": "white",
                    "border-color": "#007bff"
                });
            }
            // 如果当前时间小于等于15:00，默认选择前一个交易日，不高亮任何按钮
            
            // 刷新日历显示（更新maxDate限制）
            if (syncTimeshareStartDatePicker.calendarYear !== null && syncTimeshareStartDatePicker.calendarMonth !== null) {
                var calendarHtml = syncTimeshareStartDatePicker.generateDateCalendarWithYearMonth(
                    syncTimeshareStartDatePicker.calendarYear, 
                    syncTimeshareStartDatePicker.calendarMonth
                );
                $('#' + syncTimeshareStartDatePicker.options.calendarId).html(calendarHtml);
                syncTimeshareStartDatePicker.bindYearMonthSelectorEvents();
            }
            if (syncTimeshareEndDatePicker.calendarYear !== null && syncTimeshareEndDatePicker.calendarMonth !== null) {
                var calendarHtml = syncTimeshareEndDatePicker.generateDateCalendarWithYearMonth(
                    syncTimeshareEndDatePicker.calendarYear, 
                    syncTimeshareEndDatePicker.calendarMonth
                );
                $('#' + syncTimeshareEndDatePicker.options.calendarId).html(calendarHtml);
                syncTimeshareEndDatePicker.bindYearMonthSelectorEvents();
            }
        }, 100);
    }
    
    // 关闭同步分时数据模态框
    function closeSyncTimeshareModal() {
        // 停止轮询定时器
        stopPollingProgress();
        
        // 重置状态
        syncTimeshareTaskId = null;
        syncTimeshareTotalDays = 0;
        syncTimeshareSyncedDays = 0;
        syncTimeshareStartTime = null;
        syncTimeshareLastTimeUpdate = 0;
        $("#syncTimeshareModal").css("display", "none");
    }
    
    // 格式化时间（毫秒转 HH:MM:SS）
    function formatTime(ms) {
        var totalSeconds = Math.floor(ms / 1000);
        var hours = Math.floor(totalSeconds / 3600);
        var minutes = Math.floor((totalSeconds % 3600) / 60);
        var seconds = totalSeconds % 60;
        return String(hours).padStart(2, '0') + ':' + 
               String(minutes).padStart(2, '0') + ':' + 
               String(seconds).padStart(2, '0');
    }
    
    // 更新进度条和时间显示
    function updateSyncProgress() {
        // 如果还没有开始同步，不更新
        if (syncTimeshareTotalDays === 0 || !syncTimeshareStartTime) return;
        
        var progress = (syncTimeshareSyncedDays / syncTimeshareTotalDays) * 100;
        var progressPercent = Math.round(progress * 100) / 100; // 保留两位小数
        
        // 更新进度条宽度
        $("#syncTimeshareProgressBar").css("width", progress + "%");
        
        // 更新进度条上的百分比和天数
        $("#syncTimeshareProgressText").text(progressPercent.toFixed(2) + "% (" + syncTimeshareSyncedDays + "/" + syncTimeshareTotalDays + ")");
        
        // 更新进度详情（天数/天数）
        var progressDetail = syncTimeshareSyncedDays + " 天 / " + syncTimeshareTotalDays + " 天";
        $("#syncTimeshareProgressDetail").text(progressDetail);
        
        // 计算已同步时间（每次调用都重新计算，确保每秒更新）
        var elapsedTime = Date.now() - syncTimeshareStartTime;
        $("#syncTimeshareElapsedTime").text(formatTime(elapsedTime));
        
        // 计算预计同步时间（每10秒更新一次）
        var currentTime = Date.now();
        var estimatedTime = 0; // 预计同步时间
        
        // 如果还没有初始化时间标记，初始化为当前时间（第一次调用时）
        if (!syncTimeshareLastTimeUpdate || syncTimeshareLastTimeUpdate === 0) {
            syncTimeshareLastTimeUpdate = currentTime;
        }
        
        var timeSinceLastUpdate = currentTime - syncTimeshareLastTimeUpdate;
        
        // 只在距离上次更新超过10秒时才更新预计时间
        if (timeSinceLastUpdate >= 10000) {
            // 更新预计时间
            syncTimeshareLastTimeUpdate = currentTime;
            
            if (syncTimeshareSyncedDays > 0 && elapsedTime > 0) {
                // 根据已用时间和已同步天数，估算平均每天的耗时
                var avgTimePerDay = elapsedTime / syncTimeshareSyncedDays;
                estimatedTime = avgTimePerDay * syncTimeshareTotalDays;
                $("#syncTimeshareEstimatedTime").text(formatTime(estimatedTime));
            } else {
                // 如果还没有同步数据，显示默认值
                estimatedTime = 0;
                $("#syncTimeshareEstimatedTime").text("00:00:00");
            }
        } else {
            // 如果时间未到10秒，从DOM中读取上次的预计时间
            var estimatedTimeText = $("#syncTimeshareEstimatedTime").text();
            if (estimatedTimeText && estimatedTimeText !== "00:00:00") {
                // 解析时间文本（格式：HH:MM:SS）
                var parts = estimatedTimeText.split(':');
                if (parts.length === 3) {
                    estimatedTime = parseInt(parts[0]) * 3600000 + 
                                   parseInt(parts[1]) * 60000 + 
                                   parseInt(parts[2]) * 1000;
                }
            }
        }
        
        // 计算剩余同步时间（每秒更新）：剩余时间 = 预计同步时间 - 已同步时间
        if (estimatedTime > 0) {
            var remainingTime = Math.max(0, estimatedTime - elapsedTime); // 确保不为负数
            $("#syncTimeshareRemainingTime").text(formatTime(remainingTime));
        } else {
            $("#syncTimeshareRemainingTime").text("00:00:00");
        }
    }
    
    // 确认同步分时数据
    function confirmSyncTimeshare() {
        var symbol = currentSecuritySymbol;
        if (!symbol || symbol.trim() === "") {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        
        var startDate = syncTimeshareStartDatePicker ? syncTimeshareStartDatePicker.getSelectedDate() : $("#syncTimeshareStartDate").val();
        var endDate = syncTimeshareEndDatePicker ? syncTimeshareEndDatePicker.getSelectedDate() : $("#syncTimeshareEndDate").val();
        
        if (!startDate || !endDate) {
            $.modal.msgWarning("请选择开始日期和结束日期");
            return;
        }
        
        if (startDate > endDate) {
            $.modal.msgWarning("开始日期不能晚于结束日期");
            return;
        }
        
        // 禁用确认按钮
        $("#syncTimeshareModalConfirm").prop("disabled", true);
        
        // 先调用getInvalidTradeDates接口获取需要同步的日期列表（用于显示总天数）
        $.ajax({
            url: prefix + "time-share/invalid-dates",
            type: "GET",
            data: {
                symbol: symbol,
                startDate: startDate,
                endDate: endDate
            },
            dataType: 'json',
            success: function(data) {
                if (data.code === 0) {
                    // 获取无效交易日列表
                    var invalidDates = data.data || [];
                    
                    if (invalidDates.length === 0) {
                        $("#syncTimeshareModalConfirm").prop("disabled", false);
                        $.modal.msgSuccess("所选日期范围内的数据已完整，无需同步");
                        return;
                    }
                    
                    // 初始化同步状态
                    syncTimeshareTotalDays = invalidDates.length;
                    syncTimeshareSyncedDays = 0;
                    syncTimeshareStartTime = Date.now();
                    syncTimeshareTaskId = null;
                    syncTimeshareLastTimeUpdate = Date.now(); // 初始化时间更新标记为当前时间
                    
                    // 显示进度条
                    $("#syncTimeshareProgress").css("display", "block");
                    updateSyncProgress();
                    
                    // 一次性调用同步接口，传入所有日期范围
                    $.ajax({
                        url: prefix + "time-share/sync",
                        type: "POST",
                        data: {
                            symbol: symbol,
                            startDate: startDate,
                            endDate: endDate
                        },
                        dataType: 'json',
                        success: function(syncData) {
                            if (syncData.code === 0) {
                                // 获取任务ID
                                syncTimeshareTaskId = syncData.data;
                                
                                if (!syncTimeshareTaskId) {
                                    // 无需同步
                                    $("#syncTimeshareModalConfirm").prop("disabled", false);
                                    $.modal.msgSuccess("所选日期范围内的数据已完整，无需同步");
                                    $("#syncTimeshareProgress").css("display", "none");
                                    return;
                                }
                                
                                // 开始轮询进度
                                startPollingProgress();
                            } else {
                                $("#syncTimeshareModalConfirm").prop("disabled", false);
                                $.modal.msgError("启动同步任务失败：" + syncData.msg);
                                $("#syncTimeshareProgress").css("display", "none");
                            }
                        },
                        error: function(xhr, status, error) {
                            $("#syncTimeshareModalConfirm").prop("disabled", false);
                            $.modal.msgError("启动同步任务失败：" + error);
                            $("#syncTimeshareProgress").css("display", "none");
                        }
                    });
                } else {
                    $("#syncTimeshareModalConfirm").prop("disabled", false);
                    $.modal.msgError("获取无效交易日列表失败：" + data.msg);
                }
            },
            error: function(xhr, status, error) {
                $("#syncTimeshareModalConfirm").prop("disabled", false);
                $.modal.msgError("获取无效交易日列表失败：" + error);
            }
        });
    }
    
    // 开始轮询同步进度
    function startPollingProgress() {
        // 清除旧的定时器
        if (syncTimeshareTimer) {
            clearInterval(syncTimeshareTimer);
        }
        
        // 立即查询一次
        pollSyncProgress();
        
        // 每1秒轮询一次进度
        syncTimeshareTimer = setInterval(function() {
            pollSyncProgress();
        }, 1000);
    }
    
    // 轮询同步进度
    function pollSyncProgress() {
        if (!syncTimeshareTaskId) {
            return;
        }
        
        // 使用 try-catch 包装，避免异步操作导致的错误
        try {
            $.ajax({
                url: prefix + "time-share/sync/progress",
                type: "GET",
                data: {
                    taskId: syncTimeshareTaskId
                },
                dataType: 'json',
                timeout: 10000, // 设置10秒超时
                success: function(data) {
                if (data.code === 0 && data.data) {
                    var progressData = data.data;
                    
                    // 更新进度信息
                    syncTimeshareTotalDays = progressData.totalDays || 0;
                    // 使用已处理天数来更新进度（processedDays 或 syncedDays + failedDays）
                    var processedDays = progressData.processedDays || (progressData.syncedDays || 0) + (progressData.failedDays || 0);
                    syncTimeshareSyncedDays = processedDays;
                    
                    // 更新进度条
                    updateSyncProgress();
                    
                    // 更新当前同步日期
                    if (progressData.currentDate) {
                        $("#syncTimeshareCurrentDate").text(progressData.currentDate);
                    }
                    
                    // 检查任务状态
                    if (progressData.status === "COMPLETED") {
                        // 同步完成
                        stopPollingProgress();
                        $("#syncTimeshareModalConfirm").prop("disabled", false);
                        $.modal.msgSuccess("同步分时数据成功");
                        closeSyncTimeshareModal();
                        
                        // 检查是否有返回URL（从回测页面跳转过来的）
                        if (window.syncReturnUrl) {
                            // 延迟一下，让用户看到成功提示
                            setTimeout(function() {
                                // 跳转回回测页面
                                window.location.href = window.syncReturnUrl;
                            }, 1500);
                        } else {
                            // 刷新显示日线或5日线
                            loadSecurityData();
                        }
                    } else if (progressData.status === "FAILED") {
                        // 同步失败
                        stopPollingProgress();
                        $("#syncTimeshareModalConfirm").prop("disabled", false);
                        var errorMsg = progressData.errorMessage || "同步失败";
                        $.modal.msgError("同步失败：" + errorMsg);
                        closeSyncTimeshareModal();
                    }
                    // 如果状态是 RUNNING，继续轮询
                } else {
                    // 查询失败，可能是任务不存在
                    if (data.msg && data.msg.indexOf("任务不存在") !== -1) {
                        stopPollingProgress();
                        $("#syncTimeshareModalConfirm").prop("disabled", false);
                        $.modal.msgError("同步任务不存在或已过期");
                        closeSyncTimeshareModal();
                    }
                }
                },
                error: function(xhr, status, error) {
                    // 忽略超时错误和网络错误（可能是浏览器扩展导致的）
                    if (status === 'timeout' || status === 'abort') {
                        console.warn("查询同步进度超时或中断:", status);
                        return; // 继续轮询，不停止
                    }
                    
                    console.error("查询同步进度失败:", error);
                    // 系统服务错误，停止轮询
                    stopPollingProgress();
                    $("#syncTimeshareModalConfirm").prop("disabled", false);
                    var errorMsg = "查询同步进度失败";
                    if (xhr && xhr.responseJSON && xhr.responseJSON.msg) {
                        errorMsg = xhr.responseJSON.msg;
                    } else if (error) {
                        errorMsg = error;
                    }
                    $.modal.msgError(errorMsg);
                    closeSyncTimeshareModal();
                }
            });
        } catch (e) {
            // 捕获可能的运行时错误（如浏览器扩展导致的错误）
            console.warn("轮询同步进度时发生错误（可能是浏览器扩展导致）:", e);
            // 不停止轮询，继续尝试
        }
    }
    
    // 停止轮询进度
    function stopPollingProgress() {
        if (syncTimeshareTimer) {
            clearInterval(syncTimeshareTimer);
            syncTimeshareTimer = null;
        }
    }
    
    // 快捷日期选择
    function setQuickDateRange(days, months) {
        // 计算当前时间和最大可选日期
        var now = new Date();
        var currentHour = now.getHours();
        var currentMinute = now.getMinutes();
        var isAfter1500 = (currentHour > 15) || (currentHour === 15 && currentMinute >= 0);
        
        var todayStr = now.toISOString().split('T')[0];
        var endDate;
        
        if (days === 0) {
            // 当日：如果当前时间大于15:00，可以选择今天；否则不能选择
            if (isAfter1500) {
                endDate = todayStr;
            } else {
                // 当前时间小于等于15:00，不能选择今天，使用前一个交易日
                if (syncTimeshareEndDatePicker && syncTimeshareEndDatePicker.findPreviousTradingDay) {
                    endDate = syncTimeshareEndDatePicker.findPreviousTradingDay(todayStr);
                } else {
                    var yesterday = new Date(now);
                    yesterday.setDate(yesterday.getDate() - 1);
                    endDate = yesterday.toISOString().split('T')[0];
                }
            }
        } else {
            // 其他情况：结束日期为昨天或今天（根据当前时间）
            if (isAfter1500) {
                endDate = todayStr;
            } else {
                var yesterday = new Date(now);
                yesterday.setDate(yesterday.getDate() - 1);
                endDate = yesterday.toISOString().split('T')[0];
            }
        }
        
        var startDate;
        if (days !== undefined) {
            // 按天数计算
            if (days === 0) {
                // 当日：开始日期和结束日期相同
                startDate = endDate;
            } else {
                // 计算开始日期：往前推 (days - 1) 天，这样包含结束日期在内总共是 days 天
                // 例如：5日 = 结束日期往前推4天，包含结束日期共5天
                var date = new Date(endDate);
                date.setDate(date.getDate() - (days - 1));
                startDate = date.toISOString().split('T')[0];
            }
        } else if (months !== undefined) {
            // 按月数计算
            var date = new Date(endDate);
            date.setMonth(date.getMonth() - months);
            startDate = date.toISOString().split('T')[0];
        }
        
        // 设置日期（需要找到最近的交易日）
        if (syncTimeshareStartDatePicker && syncTimeshareStartDatePicker.findNearestTradingDay) {
            var nearestStartDate = syncTimeshareStartDatePicker.findNearestTradingDay(startDate);
            syncTimeshareStartDatePicker.setDate(nearestStartDate);
        } else {
            syncTimeshareStartDatePicker.setDate(startDate);
        }
        
        if (syncTimeshareEndDatePicker) {
            var nearestEndDate;
            if (days === 0 && isAfter1500) {
                // 当日且当前时间大于15:00，使用findNearestTradingDay
                nearestEndDate = syncTimeshareEndDatePicker.findNearestTradingDay ? 
                    syncTimeshareEndDatePicker.findNearestTradingDay(endDate) : endDate;
            } else if (days === 0 && !isAfter1500) {
                // 当日但当前时间小于等于15:00，使用findPreviousTradingDay
                nearestEndDate = syncTimeshareEndDatePicker.findPreviousTradingDay ? 
                    syncTimeshareEndDatePicker.findPreviousTradingDay(todayStr) : endDate;
            } else {
                // 其他情况，使用findNearestTradingDay
                nearestEndDate = syncTimeshareEndDatePicker.findNearestTradingDay ? 
                    syncTimeshareEndDatePicker.findNearestTradingDay(endDate) : endDate;
            }
            syncTimeshareEndDatePicker.setDate(nearestEndDate);
        } else {
            syncTimeshareEndDatePicker.setDate(endDate);
        }
    }
    
    // 绑定事件
    $(document).ready(function() {
        $("#syncTimeshareModalClose, #syncTimeshareModalCancel").on('click', function() {
            closeSyncTimeshareModal();
        });
        
        $("#syncTimeshareModalConfirm").on('click', function() {
            confirmSyncTimeshare();
        });
        
        // 快捷日期选择按钮
        $(".sync-quick-date-btn").on('click', function() {
            // 移除所有按钮的active状态
            $(".sync-quick-date-btn").css({
                "background": "#f5f5f5",
                "color": "#666",
                "border-color": "#ddd"
            });
            
            // 添加当前按钮的active状态
            $(this).css({
                "background": "#007bff",
                "color": "white",
                "border-color": "#007bff"
            });
            
            var days = $(this).data("days");
            var months = $(this).data("months");
            setQuickDateRange(days, months);
        });
    });
</script>
</body>
</html>
